错误401(未授权)使用包含JWT标头的Axios进行REST调用时

问题描述 投票:0回答:2

我正在使用JWT护照开发一个小型反应节点应用程序进行身份验证。我通过postman测试了所有端点(通过使用授权头传递令牌)并且它们正常工作。

这是从前端调用即时通讯

export const getUsersDetails=()=>{
  console.log( localStorage.getItem('jwtToken'));
  return (dispatch) => {
    return axios.get('http://localhost:3030/users',
             { headers: { 'Authorization': localStorage.getItem('jwtToken') } }
            ).then((data)=>{
                 console.log('data comming',data);
                dispatch(getUsersData(data));
            }).catch((error)=>{
              console.log('error comming',error);
                dispatch(errorgetUsersData(error));
            });
        };
}

我已经使用CORS模块启用了CORS。这就是网络调用从浏览器enter image description here看起来的样子

授权标题看起来像 authorization:[object Object], eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.....

这应该像authorization: eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.....这是我面临这个问题的原因吗?怎么克服这个?

cors cross-domain jwt axios
2个回答
1
投票

当您需要在应用中进行授权时,这取决于您完成后端的方式。如果邮递员的一切都好,那就说明你的品尝后邮递员的标题是怎样的。我使用xsrf令牌,这是我的请求标头的样子:

    {headers: 
           {"Access-Control-Allow-Headers" : "*",
            "X-XSRF-TOKEN": this.$cookie.get('XSRF-TOKEN')}
    }

也许你应该把"Access-Control-Allow-Headers" : "*"


1
投票

通过在全局分配的令牌前添加Bearer和一个空格,我可以在反应应用程序中全局配置axios,从而解决MERN堆栈上的类似问题。

axios.defaults.headers.common['Authorization'] =Bearer $ {token} ;

最初,它没有Bearer,我一直收到401状态代码。

axios.defaults.headers.common['Authorization'] = token;
© www.soinside.com 2019 - 2024. All rights reserved.