abort all Axios requests when change route use vue-router abort all Axios requests when change route use vue-router vue.js vue.js

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.