使用axios在标头中传递JWT [英] Passing JWT in headers with axios
问题描述
我创建了一个带有节点后端的小项目,并通过使用 Axios 库的REST调用来反馈前端来获取数据。但是当我用它传递标题时,我不断收到错误说 无法加载资源:服务器响应状态为401(未授权)
。我发现了两种方法,但都没有用。
I've created a small project with a node back-end and react front-end to fetch the data through REST calls i used Axios library. But when i pass the headers with it i keep getting an error saying Failed to load resource: the server responded with a status of 401 (Unauthorized)
. I found out two methods and both did not work.
它们是
export const getUsersDetails=()=>{
console.log('calling');
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));
});
};
}
和
axios.defaults.headers.common['Authorization'] = localStorage.getItem('jwtToken');
但当我使用邮递员从后端获取所需数据时。任何特殊原因导致我不断收到此未经授权的错误?
But When i use postman im getting the required data from the backend. Any particular reason why im keep getting this Unauthorized error?.
推荐答案
您需要在令牌之前连接'Bearer',就像这样:
You need to concatenate 'Bearer ' before the token, like this:
axios.defaults.headers.common['Authorization'] =
'Bearer ' + localStorage.getItem('jwtToken');
这篇关于使用axios在标头中传递JWT的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!