DEV Community

abdul waheed
abdul waheed

Posted on

Global HTTP Request using Interceptors and Axios

What are Interceptors?And how to intercept axios request and response.

If for some reason you want to inject a piece of code in a method that needs to be executed before or after the execution of that method, then interceptors are there to help you. In the following example, we created an interceptor method on Array.prototype.reverse, this method consoles the value of the array before the reverse and after the reverse.

// store original implementation in cache
var _reverse = Array.prototype.reverse;

// define your own reverse method
Array.prototype.reverse = function() {

   // before reversing array
   console.log("before reverse \n"+this.toString());

   // call original Array reverse method
   _reverse.apply(this, arguments );

   // do whatever you like after
   // the reverse has been called
       console.log("after reverse\n"+this.toString());
}

const array1 = ['one', 'two', 'three'];

array1.reverse();
   }
}
Enter fullscreen mode Exit fullscreen mode

Intercept axios request

For those who do not know what is axios? “ Axios is a promise based HTTP client for the browser and node.js.” With the help of interceptors we can modify the request and response before respective methods calls from the library. Interceptors can help us apply common functionality across all requests at one place.

const HTTP = axios.create({
 baseURL: env.API_URL,
 timeout: 60000,
});

HTTP.interceptors.request.use(
 (config) => {
  config.headers.authorization = `Bearer ${localStore.getToken()}`;
   return config;
 },
 (error) => {
   return Promise.reject(error);
 }
);

// Add a response interceptor
HTTP.interceptors.response.use(
 (response) => {
   return response;
 },
 (err) => {
        console.log(err)
 }
);
Enter fullscreen mode Exit fullscreen mode

As from the above example we can see that we created an axios instance and use two interceptors one for request and one for response. In the request interceptor we get the token from local storage and put in a header of request and in case if an error occurred during getting token it will reject the request immediately. Another one for the response, it also has two callbacks one for the response(any status code lies between 2xx) and another one for error handling.

Latest comments (0)