Reputation: 103
I got a Bearer Token and I don't know what to do with it. It's a React Project and I'm using Axios to get data from the API. My question is where does this Token go? Should I put it everytime I use Axios.get or I can store it somewhere?
Upvotes: 0
Views: 4301
Reputation: 3713
Easiest way you can add bearer authentication token to your axios instance using this pattren
let api = axios.create({
baseURL: YOUR_BASE_urL,
timeout: 7000,
headers: {
Accept: 'application/json',
'Content-Type': 'application/json'
}
});
best way consider is JWT authentication token shoud be stored in LocalStorage and write method to get token from localStorage and assign it axios instance
function addToken() {
api.defaults.headers.common['Authorization'] = !!localStorage.getItem('jwt') ? `Bearer ${localStorage.getItem('jwt')}` : '';
}
now you have axios instance and method with which you can get Token from localStorage and assign to axios instance
one step is left
You just need to execute this method before making request to axios execute function before creating api call
addToken()
Or
You can prefer adding token to you axios instance directly
let api = axios.create({
baseURL: YOUR_BASE_urL,
timeout: 7000,
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
'Authorization': "bearer " + token
}
});
Upvotes: 0
Reputation: 791
let url = "";
let body= {}
let header= {
headers: {'Authorization': "Bearer " + yourToken}
};
axios.post(url, body, header)
.then(res => {
console.log(res)
}).catch(err => {
console.log(err)
});
Upvotes: 0
Reputation: 208
You have to put in Authorization headers in every request. Refer to this answer Sending the bearer token with axios
Upvotes: 2