Getting 401 Unauthorized error even when I'm logged in

感情迁移 提交于 2020-03-06 09:31:58

问题


Posting this Q&A for whomever it might concern:

I've been working on a practice project since this course with a react front-end. The user's page on the front end does not fetch any data and gives 401 Unauthorized error( message: You are not logged in! Please log in to get access). I figured the cookies are not being sent with the get request, I've tried both axios and fetch requests. I could set the req.authorization = `Bearer ${token}` or req.cookies = ${cookies}` after locally storing token and cookies respectively, but what's the point if I have to set it manually with every request.

The route works without any bugs on postman. It shows logged in throughout the app but cannot fetch data on /me route due lack of authorization.


回答1:


Here's a simple solution I found through Github.

I created an axios instance

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*/ 

})

then modified the cors object to


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*/

})

and the config worked for the entire app.



来源:https://stackoverflow.com/questions/60314076/getting-401-unauthorized-error-even-when-im-logged-in

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!