提问者:小点点

CORS阻塞带有'Authorization'头和数据的axios请求


试图将axios post请求从Vue应用程序(localhost)发送到我的nodejs API(localhost和heroku)。
如果请求是在没有数据或头的情况下发送的,则接收响应不会有问题,但是当我添加它们时,我会收到以下错误:

Access to XMLHttpRequest at 'https://myapp.herokuapp.com/myendpoint' from origin 'http://localhost:8080'
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.

我已经尝试了不同的选择,服务器端和客户端,建议类似的问题,但没有成功。

客户端请求:

        const apiUrl = 'https://myapp.herokuapp.com/myendpoint'
        //const apiUrl = 'http://localhost:5000/myendpoint'
        
        const token = Buffer.from(`${this.userid}:${this.password}`).toString('base64')
        const data = {
          'mydata': 'some data'
        }

        axios.post(apiUrl, data, {
          headers: {
            Authorization: "Basic " + token 
          }
        }).then( res => {
          console.log(res)
        }).catch( err => {
          console.log(err)
        })

服务器endpoint:

app.post("/myendpoint", (req, res) => {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Methods", "*");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");

    res.send('This is the API\'s response')    
})

我尝试了一些答案:
对预飞行请求的响应没有通过访问控制检查
Nodejs Express CORS问题的'access-control-allow-origin'
https://www.moesif.com/blog/technical/CORS/authoritial-guide-to-cors-cross-origin-resource-sharing-for-rest-apis/
使用axios时CORS授权问题
如何使用axios发送授权头


共1个答案

匿名用户

我认为使用全局中间件定义cors会更好。首先,使用npm i cors安装cors

然后,我将展示一个如何使用该包的示例。

const express = require('express');
const cors = require('cors');

const app = express();

app.use(cors());

// your routes and things here...

然后,确保前端还在Axios请求中使用设置为truewithCredentials。这样做是为了确保正确发送报头。

axios.post(apiUrl, data, {
  headers: {
    Authorization: "Basic " + token 
  },
  withCredentials: true,
}).then(() => ...);

有时,如果手动定义access-control-*,可能会忘记一些东西。这就是为什么我建议您使用cors