首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用vue-router更改路由时中止所有Axios请求

使用vue-router更改路由时中止所有Axios请求
EN

Stack Overflow用户
提问于 2018-07-20 17:24:56
回答 2查看 17.2K关注 0票数 17

当我使用vue-router更改路由时,如何在完成之前中止/取消Axios请求。

当用户打开页面时,它会自动发送axios请求来获取一些数据,但用户不等待响应,就会通过vue-router改变路由,这将是大量的Axios请求

那么我的问题有什么解决办法吗?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-07-20 20:37:13

基本上,您必须生成一个全局取消令牌

代码语言:javascript
复制
const CancelToken = axios.CancelToken;
const source = CancelToken.source();

并通过在config参数中传递来在所有请求中使用它

GET请求:

代码语言:javascript
复制
axios.get('/user/12345', {
  cancelToken: source.token
}).catch(function(thrown) {
  if (axios.isCancel(thrown)) {
    console.log('Request canceled', thrown.message);
  } else {
    // handle error
  }
});

POST请求:

代码语言:javascript
复制
axios.post('/user/12345', {
  name: 'new name'
}, {
  cancelToken: source.token
})

然后,在vue路由器beforeEach导航卫士中,您可以使用以下命令取消所有请求:

代码语言:javascript
复制
source.cancel('Operation canceled by the user.');

这里是官方的axios取消指南:https://github.com/axios/axios#cancellation

票数 17
EN

Stack Overflow用户

发布于 2020-01-15 03:16:58

来自@fabruex的答案是正确的。我只想在这里补充一下,如果你有很多api调用,那么你必须在每个api调用配置中传递取消令牌。为了减少代码,您可以创建axios实例并添加请求拦截器,该拦截器将添加通用取消令牌,然后当取消完成或路由更改时,您可以为令牌分配一个新值。

代码语言:javascript
复制
// 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

您可以创建一个类并创建一个可以更新的实例

代码语言:javascript
复制
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());

票数 7
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51439338

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档