-3

I am using Vue js for the FrontEnd and Node js(express) on Backend. Tried so many of the solution on internet and not sure what is going wrong.

Note: I am using build or production version(dist) of Vue.js not in the development mode.

Problem : I am making a call to another api or IP on local networkhttp://192.168.161.43/cgi-bin/remote.cgi? from the frontend and I get the CORS issue as below

Access to XMLHttpRequest at `'http://192.168.161.43/cgi-bin/remote.cgi?S'` from origin 'http://localhost:5000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Here is how code for FrontEnd and Backend look like.

In main.js file in Vue

    import Vue from 'vue'
    import App from './App.vue'
    import router from './router'
    import axios from 'axios';
    
    Vue.http.headers.common['Access-Control-Allow-Origin'] = true
    Vue.http.headers.common['Access-Control-Request-Method'] = '*'
    Vue.http.options.emulateJSON = true
    Vue.use(VueToastify, { position: "top-right" });
    new Vue({
        router,
        store,
        vuetify,
        render: h => h(App)
    }).$mount('#app')

From eLock.vue, I am sending a request to the IP(http://192.168.161.43/cgi-bin/remote.cgi?) and its get blocked in the Browser. The code for it is below

<template>
ELOCK Component
</template>

<script>

import axios from "axios";
export default {
  name: "eLockIn",
  components: {  },
  data() {
    return {
      ProxyUrl: "http://192.168.161.43/cgi-bin/remote.cgi?",
    };
  },
  watch: {
    /* sliderValue() {
      this.updateSlider()
    } */
  },
  created() {},
  mounted() {
    this.reload()
    /* 
    setInterval(()=>{
      axios.post(this.ProxyUrl + 'S')
      setTimeout(() =>{
        this.img="http://192.168.161.41/screen.jpg?rand_number=" + Math.random()
      }, 2000)
    }, 3000) */

  computed: {},
  methods: {
    reload() {
      axios.post(this.ProxyUrl + 'S')
      setTimeout(() => {
        this.img = "http://192.168.161.43/screen.jpg?rand_number=" + Math.random();
      }, 2000);
    },
    LockIn() {
      axios.post(this.ProxyUrl + "8");
      setTimeout(() => {
        this.reload()
      }, 1000);
      
    },
    Spectra() {
      axios.post(this.ProxyUrl + "C");
      setTimeout(() => {
        this.reload()
      }, 1000);
    },
    Scope() {
      axios.post(this.ProxyUrl + "4");
      setTimeout(() => {
        this.reload()
      }, 1000);
    },
    Measure() {
      axios.post(this.ProxyUrl + "F");
      setTimeout(() => {
        this.reload()
      }, 2000);
    },
    Setup() {
      axios.post(this.ProxyUrl + "0");
      setTimeout(() => {
        this.reload()
      }, 2000);
    },
    /* ---------------------------------- */
    Button_1() {
      axios.post(this.ProxyUrl + "9");
      setTimeout(() => {
        this.reload()
      }, 2000);
    },
    Button_2() {
      axios.post(this.ProxyUrl + "D");
      setTimeout(() => {
        this.reload()
      }, 2000);
    },
    Button_3() {
      axios.post(this.ProxyUrl + "5");
      setTimeout(() => {
        this.reload()
      }, 2000);
    },
    Button_4() {
      axios.post(this.ProxyUrl + "1");
      setTimeout(() => {
        this.reload()
      }, 2000);
    },
    Button_5() {
      axios.post(this.ProxyUrl + "A");
      setTimeout(() => {
        this.reload()
      }, 2000);
    },
    /* ---------------------------------- */
</script>

<style lang="scss">

</style>

In server.js, here is the express code

const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const path = require('path');
const cors = require('cors');

// Initialize the app
const app = express();

// Add headers before the routes are defined
app.use(function (req, res, next) {

// Website you wish to allow to connect
res.setHeader('Access-Control-Allow-Origin', 'http://192.168.161.43/cgi-bin/remote.cgi?');

// Request methods you wish to allow
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');

// Request headers you wish to allow
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');

// Set to true if you need the website to include cookies in the requests sent
// to the API (e.g. in case you use sessions)
res.setHeader('Access-Control-Allow-Credentials', true);

// Pass to next layer of middleware
next();

});

app.use("/api", require("./routes/forgetPassword"));
app.use("/Users", require("./routes/users"));
app.use("/measurement", loadProfile, require("./routes/measurement"));
app.get('/', (req, res) => {
    res.sendFile(path.join(__dirname, 'dist/index.html'));

})

app.use(express.static(path.join(__dirname, 'dist')));

const PORT = process.env.PORT || 5000;

app.listen(PORT, () => {
    console.log(`Server started on port ${PORT}`);
})

The worse part is this that I tried many solutions and the error message don't change.

Mehtab
  • 15
  • 1
  • 7
  • Why do you manually set the `Access-Control` headers instead of using `cors`? What is `http://192.168.161.43/cgi-bin/remote.cgi?`? Is it the backend, the web frontend or another API? `res.setHeader('Access-Control-Allow-Origin', 'http://192.168.161.43/cgi-bin/remote.cgi?');` has to contain the URL of the web frontend or a wildcard. It makes no sense to add these headers: `Vue.http.headers.common['Access-Control-Allow-Origin'] = true Vue.http.headers.common['Access-Control-Request-Method'] = '*'` – jabaa May 10 '22 at 12:44
  • `res.setHeader('Access-Control-Allow-Origin', 'http://192.168.161.43/cgi-bin/remote.cgi?');` has to either be `res.setHeader('Access-Control-Allow-Origin', '*');` or `res.setHeader('Access-Control-Allow-Origin', 'http://localhost:5000');` – jabaa May 10 '22 at 12:59

1 Answers1

-2

First install cors if you don't have it

npm i cors

Then use it in your express app (server.js I suppose)

const cors = require('cors');
app.use(cors({
   origin: ['https://www.example.com']
}));

or

const cors = require('cors');
app.use(cors({
  origin: '*'
}));
patonjo
  • 440
  • 4
  • 13
  • You can see the `cors` package in the code in the question. The OP already sets the `Allow-Origin` headers, but either the URL is wrong or that's not the problem. – jabaa May 10 '22 at 12:50
  • Yes I can see that your are requiring cors package, but I don't see that you are using it. – patonjo May 10 '22 at 12:53
  • Please explain the current problem and how `cors` would help here. A code without explanation isn't useful. What does `cors` do that isn't already done in the code? – jabaa May 10 '22 at 12:56