VUE JS和Node(Express)JS服务器,NO' Access-Control-Allow-Origin'标题存在于请求的资源上

发布于 2025-01-27 12:19:25 字数 4870 浏览 2 评论 0原文

我正在使用VUE JS进行前端和节点JS(Express)的后端。在互联网上尝试了许多解决方案,但不确定出了什么问题。

注意:我正在使用Vue.js的构建或生产版本(DIST),而不是在开发模式下。

问题:我正在本地网络上的另一个API或IP打电话http://192.168.161.43/cgi-bin/remote.cgi?从前端

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.

发出是前端和后端的代码的样子。

在vue中的main.js文件中

    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')

,我将请求发送到IP(http://192.168.161.43/cgi-bin/remote.cgi?),并且它被阻止浏览器。它的代码

<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>

在server.js中,这是明确的代码,

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}`);
})

更糟糕的是我尝试了许多解决方案,而错误消息不会更改。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

不再见 2025-02-03 12:19:25

首先安装CORS,如果您没有它

npm i cors

,请在Express App(我想Server.js)

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

const cors = require('cors');
app.use(cors({
  origin: '*'
}));

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: '*'
}));
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文