Skip to content

Instantly share code, notes, and snippets.

@dekadentno
Last active August 15, 2020 15:45
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save dekadentno/d60f17d2e4176cb516331b99c296f983 to your computer and use it in GitHub Desktop.
Save dekadentno/d60f17d2e4176cb516331b99c296f983 to your computer and use it in GitHub Desktop.
axios request interceptor for setting token in header and response interceptor for refresh token and repeat last api call
axios.interceptors.request.use(function(config) {
let userToken = localStorage.getItem('token');
if (userToken) {
axios.defaults.headers.common['Authorization'] = 'Bearer ' + userToken;
config.headers['Authorization'] = 'Bearer ' + userToken;
}
return config;
});
axios.interceptors.response.use(function(response) {
// console.log('api response ok');
return response;
}, function (error) {
let code = parseInt(error.message.replace(/\D/g, ''));
if (code === 401) { // status code for expired token
// get token
let token = localStorage.getItem('token');
if (!token) {
window.location = '/login'; // if there is no token in local storage navigate to login
return;
}
somehowRefreshToken(); // handle in your own way
return axios.request(error.config); // repeat last API call
}
return Promise.reject(JSON.parse(JSON.stringify(error)));
});
@usoftglobal
Copy link

somehowRefreshToken() ???

@dekadentno
Copy link
Author

somehowRefreshToken() ???

@CUIZIWEI

You'll have to handle it your own way. Meaning, you'll probably have to make an API call to get a new token. After that, you'll store it in the cookie, some central state or wherever you were storing it before.

@tokarev-photographer
Copy link

But what about the state in the store?
If you repeat the request using axios.request (error.config), the request will be executed, but the data will not be written to the vuex store. We repeated the request, but did not execute the action.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment