Axios: how to cancel request inside request interceptor properly?

Axios v0.22.0 and higher

As per the documentation, cancellation is now pretty straightforward with the AbortController class

instance.interceptors.request.use(config => {
  /* some logic */
  const controller = new AbortController();

  if (needToCancelRequest) {
    controller.abort();
  }

  return {
    ...config,
    signal: controller.signal
  };
});

Browser Compatibility

You might be tempted to do a pretty concise signal: AbortSignal.abort() instead. Please, note that it is much less supported than the solution above. See AbortSignal.abort() vs new AbortController().abort() compatibility.

Axios before v0.22.0

This is a solution taken from the axios issue on github

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

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)