Reputation: 17383
I make a class to create an axios api service. inside this class I fetch token(I got it from server and set it on cookie) from cookie.
const api = axios.create({
headers: {
common: {
'Content-Type': 'application/json'
},
post: {
}
}
});
const cookies = parseCookies()
const token = cookies.token;
if (token && token !== 'undefined') {
api.defaults.headers.common['Authorization'] = 'Bearer ' + token
}
because I import this api service from above component:
import api from "../../../services/httpService";
after login user, for another api calls cookie is null .
I think I have two solutions:
I pass token to each api call like:
const config = {
headers: { Authorization: `Bearer ${cookies.token}` }
};
api.get('profile',config).then((res) => {
I don't want use this solution.
Upvotes: 0
Views: 79
Reputation: 12787
When login success, you set token for cookies. And you should update a token for axios instance in this step.
// ... set token in cookies
api.defaults.headers.common['Authorization'] = 'Bearer ' + token
And you don't need this logic when create instance:
const cookies = parseCookies()
const token = cookies.token;
if (token && token !== 'undefined') {
api.defaults.headers.common['Authorization'] = 'Bearer ' + token
}
Upvotes: 1