【问题标题】:CORS blocking axios request with 'Authorization' Header and DataCORS 使用“授权”标头和数据阻止 axios 请求
【发布时间】:2021-06-12 19:35:31
【问题描述】:

尝试从 Vue 应用程序(本地主机)向我的 nodejs API(本地主机和 heroku)发送 axios 发布请求。
如果发送的请求没有数据或标头,则接收响应没有问题,但是一旦添加它们,我就会收到以下错误:

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

服务器端点:

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

我尝试的一些答案:
Response to preflight request doesn't pass access control check
Nodejs Express CORS issue with 'Access-Control-Allow-Origin'
https://www.moesif.com/blog/technical/cors/Authoritative-Guide-to-CORS-Cross-Origin-Resource-Sharing-for-REST-APIs/
CORS authorization issue while using axios
How to send authorization header with axios

【问题讨论】:

    标签: node.js express axios cors


    【解决方案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

    【讨论】:

    • 感谢您的回答,不知道为什么它被否决了...我还需要设置一些 cors 选项:` const corsOptions = { origin: 'localhost:8080', credentials: true , 方法: ["POST"], maxAge: 3600 } app.use(cors(corsOptions)) `
    猜你喜欢
    • 2019-05-30
    • 2016-12-28
    • 2019-11-02
    • 1970-01-01
    • 2019-10-01
    • 2014-09-23
    • 2019-11-11
    • 2017-08-20
    • 1970-01-01
    相关资源
    最近更新 更多