当我使用vue-router更改路由时,如何在完成之前中止/取消Axios请求。
当用户打开页面时,它会自动发送axios请求来获取一些数据,但用户不等待响应,就会通过vue-router改变路由,这将是大量的Axios请求
那么我的问题有什么解决办法吗?
发布于 2018-07-20 20:37:13
基本上,您必须生成一个全局取消令牌
const CancelToken = axios.CancelToken;
const source = CancelToken.source();并通过在config参数中传递来在所有请求中使用它
GET请求:
axios.get('/user/12345', {
cancelToken: source.token
}).catch(function(thrown) {
if (axios.isCancel(thrown)) {
console.log('Request canceled', thrown.message);
} else {
// handle error
}
});POST请求:
axios.post('/user/12345', {
name: 'new name'
}, {
cancelToken: source.token
})然后,在vue路由器beforeEach导航卫士中,您可以使用以下命令取消所有请求:
source.cancel('Operation canceled by the user.');这里是官方的axios取消指南:https://github.com/axios/axios#cancellation
发布于 2020-01-15 03:16:58
来自@fabruex的答案是正确的。我只想在这里补充一下,如果你有很多api调用,那么你必须在每个api调用配置中传递取消令牌。为了减少代码,您可以创建axios实例并添加请求拦截器,该拦截器将添加通用取消令牌,然后当取消完成或路由更改时,您可以为令牌分配一个新值。
// 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.
编辑以回答@Suneet Jain
您可以创建一个类并创建一个可以更新的实例
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());
您可以导入该实例cancelSource,并在需要时调用cancel。例如,当您注销时,可以调用cancel来取消所有具有cancelSource.getSource()给出的取消令牌的请求
所以在注销之后
cancelSource.cancel(‘取消’);
当用户再次登录时,为该全局实例设置新的取消令牌
cancelSource.setSource(axios.CancelToken.source());
https://stackoverflow.com/questions/51439338
复制相似问题