Last active
August 15, 2020 15:45
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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))); | |
}); |
somehowRefreshToken() ???
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.
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
somehowRefreshToken() ???