'Vue JS and Node(express) js server, No 'Access-Control-Allow-Origin' header is present on the requested resource [duplicate]

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.



Solution 1:[1]

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: '*'
}));

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 patonjo