In my Vue.js project (main.js), I implemented an axios interceptor for handling refresh tokens. The goal is to automatically get a new token using the refresh_token when a 401 error status code is received, and then retry the failed request with the new token. However, if the refresh token itself is invalid, I need to redirect the user to the login page and stop any further axios requests.
Unfortunately, I encountered two issues. Firstly, when the refresh token is invalid, the application gets stuck in a loop of making repeated API calls to refresh the token, resulting in multiple "duplicate navigation" errors in the console. Secondly, I am unable to properly catch the error in the catch block as the execution always falls into the then block, leading to an undefined response.
axios.interceptors.response.use((response) => {
return response
},
function (error) {
const originalRequest = error.config;
if (error.response.status === 401) {
axios.post(process.env.VUE_APP_BASE_URL + process.env.VUE_APP_REFRESH_TOKEN,
{
"refresh_token": localStorage.getItem("refresh_token")
})
.then(res => {
localStorage.setItem("token", "Bearer " + res.data.result.access_token);
originalRequest.headers['Authorization'] = localStorage.getItem("token");
return axios(originalRequest);
}).catch(error=>{
console.log(error);
router.push({'name':'login'})
})
}
});