Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing JWT in headers with axios

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?.

like image 872
Madushika Perera Avatar asked May 26 '17 17:05

Madushika Perera


People also ask

How do I send a bearer token in header?

The token is a text string, included in the request header. In the request Authorization tab, select Bearer Token from the Type dropdown list. In the Token field, enter your API key value. For added security, store it in a variable and reference the variable by name.


1 Answers

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

axios.defaults.headers.common['Authorization'] = 
                                'Bearer ' + localStorage.getItem('jwtToken');
like image 181
dplaza Avatar answered Oct 24 '22 00:10

dplaza