node.js - axios 授权 header /CORS 错误

标签 node.js reactjs rest react-native axios

我正在使用与 axios 的 react 来获取一些信息。我正在向 auth 用户发送 JWT token ,我在控制台浏览器中收到响应

"Access to XMLHttpRequest at 'https://beer-tonight.herokuapp.com/beer/getBeerStatus' from origin 'http://localhost:3000' has been blocked by CORS policy: Request header field authorization is not allowed by Access-Control-Allow-Headers in preflight response."

这是我的代码:

componentWillMount(){

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


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

错误:

enter image description here

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

postman 输入:

enter image description here

附注我已经添加了:

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();

最佳答案

您已经编写了授权:

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

但是 header 是 Authorization ,因为您已经在 axios 中使用过,请尝试更改它并查看它是否有效,

关于node.js - axios 授权 header /CORS 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54031193/

相关文章:

node.js - 在 Typescript 中编写和运行 node.js 应用程序

javascript - 如何使用 React 测试库测试 HTML 内容

javascript - 为什么会抛出这个异常? Uncaught ReferenceError : React is not defined

http - 如何以 RESTful 方式实现 "views"计数器?

javascript - Mongoose 找到下一个对象

node.js - 连接到 nodejs https 服务器时连接重置

c# - “The JSON value could not be converted to System.String” 尝试调用 Controller 端点时

python - 如何提高 REST API 的性能?

node.js - RabbitMQ 的 AMQP (Node.js) 过早关闭连接

javascript - 使用别名配置 Webpack 4,Babel 7 构建 React 组件库