Passing JWT in headers with axios

妖精的绣舞 提交于 2019-12-20 10:29:59

问题


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.

They are

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

and

axios.defaults.headers.common['Authorization'] = localStorage.getItem('jwtToken');

But When I use postman I am getting the required data from the backend. Any particular reason why I keep getting this Unauthorized error?.


回答1:


You need to concatenate 'Bearer ' before the token, like this:

axios.defaults.headers.common['Authorization'] = 
                                'Bearer ' + localStorage.getItem('jwtToken');


来源:https://stackoverflow.com/questions/44207197/passing-jwt-in-headers-with-axios

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