axios 如何在Vue js中取消相同的请求?

iecba09b  于 2022-11-05  发布在  iOS
关注(0)|答案(1)|浏览(212)

我正在使用axios〈0.22版本,所以我可以使用cancelToken,但我不明白如何使用它,我尝试了,但它不工作。请帮助我。如何取消请求,如果他们调用相同的端点?

let req = {}
const authInterceptors = (cfg) => {
  const config = cfg;
  req = cfg;
  config.headers.common['X-XSRF-TOKEN'] = antiForgeryToken;
  if (req[config.url]) {
    req[config.url].cancel('Automatic cancellation')
  }

  const axiosSource = axios.CancelToken.source()
  req[config.url] = { cancel: axiosSource.cancel }
  config.cancelToken = axiosSource.token
  return config;
};
const errorInterceptors = (error) => {
  return Promise.reject(error);
};
const httpClient = axios.create({
  headers: { 'Cache-Control': 'no-cache' },
  adapter: throttleAdapterEnhancer(<AxiosAdapter>axios.defaults.adapter, { threshold: 3 * 1000 }),
});

httpClient.interceptors.request.use(authInterceptors, errorInterceptors);
q9yhzks0

q9yhzks01#

首先,只需根据文档了解CancelToken
从v0.22.0开始已弃用,不应在新项目中使用
要使用CancelToken,只需3个步骤:
1.创建CancelToken
1.将令牌分配给请求
1.在CancelToken上调用方法

const CancelToken = axios.CancelToken;
const source = CancelToken.source();

axios.post('/user/12345', {
  name: 'new name'
}, {
  cancelToken: source.token
})

// cancel the request (the message parameter is optional)
source.cancel('Operation canceled by the user.');

const CancelToken = axios.CancelToken;
let cancel;

axios.get('/user/12345', {
  cancelToken: new CancelToken(function executor(c) {
    // An executor function receives a cancel function as a parameter
    cancel = c;
  })
});

// cancel the request
cancel();

文件:https://axios-http.com/docs/cancellation

相关问题