Axios: how to cancel request inside request interceptor properly?

混江龙づ霸主 提交于 2019-12-07 07:06:59

问题


I want to cancel the request if there's no token so I do like this:

instance.interceptors.request.use(config => {
  if (!getToken()) {
    console.log("interceptors: no access token");
  } else {
    config.headers.Authorization = "Bearer " + getToken().accessToken;
    return config;
  }
});

But in negative scenario there's an error TypeError: Cannot read property 'cancelToken' of undefined.


回答1:


You cannot use the token inside the interceptors but instead throw Cancel

axios.interceptors.response.use(function (response) {
  throw new axios.Cancel('Operation canceled by the user.');
}, function (error) {
  return Promise.reject(error);
});

Refer to this post: https://github.com/axios/axios/issues/583




回答2:


here is the solution

import axios from 'axios';

const CancelToken = axios.CancelToken;
let cancel;

axios.interceptors.request.use((config) => {

  if (cancel) {
    cancel(); // cancel request
  }

  config.cancelToken =  new CancelToken(function executor(c)
    {
      cancel = c;
    })

  return config

}, function (error) {
  return Promise.reject(error)
});



来源:https://stackoverflow.com/questions/50461746/axios-how-to-cancel-request-inside-request-interceptor-properly

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