Within my Vue application, I've implemented a response interceptor:
axios.interceptors.response.use(function (config) {
return config;
}, error => {
if (error.response.status !== 401) {
return new Promise((resolve, reject) => {
reject(error);
});
}
if (error.response.status === 401 && error.response.data.message === 'Token Expired') {
this.store.dispatch('auth/refreshToken').then(aToken => {
var config = error.config;
axios.defaults.headers.common['Authorization'] = 'Bearer ' + aToken;
return new Promise((resolve, reject) => {
axios.request(config).then(response => {
console.log(response);
resolve(response);
}).catch((error) => {
reject(error);
});
});
});
}
});
The focus here is on refreshing the token and reattempting the last request with the updated token.
An issue arises when considering a specific component, Product.vue
. For example, a request is made to the /products
endpoint upon mounting this component. The retrieved products are stored in a data variable called products
. If a user is currently on the /dashboard
route and their session expires while they're away, a subsequent visit to the /products
route triggers a 401 response interception event. The interceptor will update the token and retry the failed request with the new token.
The challenge lies in the fact that the new API call triggered by the interceptor doesn't originate from the original Product
component. As a result, any retrieved data is lost, leading to an empty view for the end-user.
Is there a method to identify the component responsible for the initial request within the interceptor and trigger a remount? Attempts such as using $router.push('/products')
lead to navigation restrictions due to being already on the target route.
Alternatively, is it possible to manage the promise returned by the interceptor within the Product component?