abort all Axios requests when change route use vue-router
Basically you have to generate a global cancel token
const CancelToken = axios.CancelToken;const source = CancelToken.source();
and use it in all your requests by passing it in the config parameter
GET request:
axios.get('/user/12345', { cancelToken: source.token}).catch(function(thrown) { if (axios.isCancel(thrown)) { console.log('Request canceled', thrown.message); } else { // handle error }});
POST request:
axios.post('/user/12345', { name: 'new name'}, { cancelToken: source.token})
Then, within a vue-router beforeEach
navigation guard you can cancel all requests using:
source.cancel('Operation canceled by the user.');
Here's the official axios guide for cancellation: https://github.com/axios/axios#cancellation
Answer from @fabruex is correct. I just wanted to add here that if you have lot of api calls then you have to pass cancellation token in each api call config. In order to reduce that code, you can create axios instance and add request interceptor which will add that common cancellation token and then you can assign a new value to token when cancellation is done or your route has changed.
// Some global common cancel token sourcelet cancelSource = axios.CancelToken.source();// Request interceptorexport const requestInterceptor = config => { config.cancelToken = cancelSource.token; return config;};// Add request interceptor like thisconst request = axios.create({ baseURL: SOME_URL });request.interceptors.request.use(requestInterceptor);// Now you can use this axios instance like thisawait request.get('/users');// andawait request.post('/users', data);// When you will cancelcancelSource.cancel('Your cancellation message');// And all the api calls initiated by axios instance which has request interceptor will be cancelled.
Edit to answer @Suneet Jain
You can create a class and create an instance which you can update
class CancelToken { constructor(initialValue) { this.source = initialValue; } getSource() { return this.source; } setSource(value) { this.source = value; } cancel() { this.source.cancel(); }}export const cancelSource = new CancelToken(axios.CancelToken.source());
You can import that instance cancelSource
and call cancel when required e.g. when you logout, you can call to cancel all request which have cancellation token given by cancelSource.getSource()
So after logout
cancelSource.cancel('CANCELLED');
And when again user will login, set new cancellation token to this global instance
cancelSource.setSource(axios.CancelToken.source());