【问题标题】:axios autohorization headers / CORS erroraxios 授权标头/CORS 错误
【发布时间】:2019-05-30 13:38:12
【问题描述】:

我正在使用 react with axios 来获取一些信息。我正在向身份验证用户发送 JWT 令牌并在控制台浏览器中得到响应

“从源 'http://localhost:3000' 访问 'https://beer-tonight.herokuapp.com/beer/getBeerStatus' 的 XMLHttpRequest 已被 CORS 策略阻止:不允许请求标头字段授权通过预检响应中的 Access-Control-Allow-Headers。”

这是我的代码:

componentWillMount(){

    let token = localStorage.getItem('token');


    axios.get('https://beer-tonight.herokuapp.com/beer/getBeerStatus', {headers: {Authorization : 'Bearer ' + token}}).then(
    result => {
        console.log('yey');
    });
}

错误:

当我使用 POSTMAN 时,我得到了正确的答案。

邮递员输入:

附言我已经添加了:

app.use((req, res,next)=>{
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PATCH, DELETE');
res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorisation');
next();

【问题讨论】:

  • 你用的是chrome,对吧?
  • 是的,我正在使用 chrome
  • 有一个小错字“授权”应该是您在标题键中的内容。

标签: node.js reactjs rest react-native axios


【解决方案1】:

你写过Authorisation:

res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorisation');

但是标题是Authorization,就像您在 axios 中使用的那样,尝试更改它并查看它是否有效,

【讨论】:

    【解决方案2】:

    我相信您收到的 cors 错误来自您的 node.js api。 (https://beer-tonight.herokuapp.com/beer/getBeerStatus)

    由于主机不是同源(beer-tonight.herokuapp.comlocalhost 不匹配),您需要为您的 node.js 服务器启用 cors。

    如果您使用的是快递:

    const express = require('express');
    const cors = require('cors');
    const app = express();
    
    app.use(cors());
    
    // ...
    

    来源: here

    Hapi.js:

    server.connection({ routes: { cors: true } })
    

    来源: here

    启用 CORS 后,一切都会顺利进行。 More on CORS

    【讨论】:

      猜你喜欢
      • 2020-01-05
      • 2017-11-23
      • 2017-03-07
      • 2021-02-21
      • 2019-03-20
      • 2020-10-27
      • 2021-06-12
      • 2020-05-14
      • 2017-08-18
      相关资源
      最近更新 更多