loading...
Cover image for How to intercept a request with Axios

How to intercept a request with Axios

deesouza profile image Diego Souza ・1 min read

Maybe, in your application you need to do a request with Axios using a token. But, you don't have a token yet. So, the application makes a request and then return an error with status code 401.

Fortunately, the Axios have a middleware that can help us to intercept the requests. For this, use the interceptors of instance of Axios thas was created.

import axios from 'axios';

const api = axios.create({
  baseURL: 'https://api.spotify.com/v1/',
});

api.interceptors.request.use(
  (request) => {
    if (api.defaults.headers.authorization) return request;

    throw new axios.Cancel('Token is not available. Do login, please.');
  },
  (error) => {
    return Promise.reject(error);
  },
);

export default api;

This code will avoid that the application from making the request and showing a error in the browser's console. The code check if exists a token in property Authorization, if a token is not found, the request won't be executed, returning an error from own Axios.

throw new axios.Cancel('Token is not available. Do login, please.');

This function Cancel from Axios is very important.

Do you know any other way to do this? Share with the community.

Posted on by:

Discussion

pic
Editor guide
 

so you intersected and not really canceled. its like an if statement injected o the axios client, to be checked before send. so, something that isn't started can not be canceled.

Still, the use of this intersector is good.

 

You have reason. I modified the title of the post. Thanks a lot.