abort all Axios requests when change route use vue-router

梦想与她 提交于 2020-06-25 09:06:21

问题


how can i abort / cancel Axios request before complete when i change route use vue-router.

when user open page it automatically send axios request to get some data, but user don't waiting to get response then he is changing route by vue-router it will be a lot of Axios requests

so is there any solve to my problem


回答1:


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




回答2:


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 source

let cancelSource = axios.CancelToken.source();

// Request interceptor

export const requestInterceptor = config => {
  config.cancelToken = cancelSource.token;
  return config;
};

// Add request interceptor like this
const request = axios.create({ baseURL: SOME_URL });
request.interceptors.request.use(requestInterceptor);


// Now you can use this axios instance like this

await request.get('/users');

// and

await request.post('/users', data);

// When you will cancel
cancelSource.cancel('Your cancellation message');

// And all the api calls initiated by axios instance which has request interceptor will be cancelled.


来源:https://stackoverflow.com/questions/51439338/abort-all-axios-requests-when-change-route-use-vue-router

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!