Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Axios: how to cancel request inside request interceptor properly?

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.

like image 365
TotalAMD Avatar asked May 22 '18 07:05

TotalAMD


People also ask

How do I cancel an interceptor request?

interceptors. request. use(config => { /* some logic */ return { ... config, cancelToken: new CancelToken((cancel) => cancel('Cancel repeated request')) }; });

How does axios cancel work?

Axios supports a limited mechanism for cancelling requests. The syntax is straightforward: you pass a cancelToken option to your Axios request, and calling cancel() makes your request error out.


4 Answers

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

like image 167
grane2212 Avatar answered Sep 18 '22 05:09

grane2212


For later googlers, this is a good solution taken from the axios issue on github

instance.interceptors.request.use(config => {
  /* some logic */
  return {
    ...config,
    cancelToken: new CancelToken((cancel) => cancel('Cancel repeated request'))
  };
});

This is pretty much what Vijay proposed but in a more concise form.

like image 34
Kirill Taletski Avatar answered Sep 22 '22 05:09

Kirill Taletski


@Kirill Taletski's answer solve this perfectly, but add one line:

const CancelToken = Axios.CancelToken;

then ,it gonna be like this :

instance.interceptors.request.use(config => {
  /* some logic */
  const CancelToken = Axios.CancelToken;
  return {
    ...config,
    cancelToken: new CancelToken((cancel) => cancel('Cancel repeated request'))
  };
});
like image 26
jaycethanks Avatar answered Sep 20 '22 05:09

jaycethanks


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)
});

like image 25
Vijay sadhu Avatar answered Sep 19 '22 05:09

Vijay sadhu