即使登录后也会出现401未经授权的错误

问题描述 投票:-1回答:1

向可能关心的人发布此问答:

从本课程开始,我就一直在与React前端一起从事实践项目。前端的用户页面不会获取任何数据,而是提供401 Unauthorized error( message: You are not logged in! Please log in to get access)。我发现cookie没有与get请求一起发送,我尝试了axios和fetch请求。我可以分别在本地存储令牌和cookie之后设置req.authorization = `Bearer ${token}`req.cookies = ${cookies}`,但是如果我必须在每个请求中手动设置它,那有什么用呢?

该路线运作正常,邮递员没有任何错误。它显示整个应用程序已登录,但由于缺少授权而无法在/me路由上获取数据。

node.js cookies axios cross-domain request-headers
1个回答
-1
投票

这是我通过Github找到的简单解决方案。

我创建了axios实例

axios.create({

   baseURL:'http://192.168.0.11:5000/', //URL of your backend in terms of IP

   withCredentials: true, //Allows cookies

   headers:{'Authorization':`Bearer ${localStorage.getItem('token')`} /*Sets Authorization header to desired value*/ 

})

然后将cors对象修改为


app.use(cors({

  origin:'http://localhost:3000', //URL of your frontend

  credentials:true, //Allows cookies

  headers:['Content-Length','Content-Type','Authorization'] /*Sets authorization header along with deafult headers*/

})

并且该配置适用于整个应用程序。

© www.soinside.com 2019 - 2024. All rights reserved.