CodeSource code example

How To Use Axios Interceptors


In this article, you will learn how to use Axios Interceptors on your requests and responses.

The Axios Interceptors works by intercepts all the requests and responses before they are handled by then() or catch() on the current instance.

Let’s say you want to put an authorization token inside request header, you can use this:

// intercepting requests
axios.interceptors.request.use(function (config) {
    config.headers.Authorization = token;
    return config;
  }, function (error) {
    // Do something with request error
    return Promise.reject(error);
});

On interception responses, let’s say we want to display on the console if we got a 401 error, which means unauthorized request, we can do something like this:

// intercepting responses
axios.interceptors.response.use(function (response) {
  // Do something with response data
  return response;
}, function (error) {
  // Do something with response error
  if(error.response.status === 401){
    console.log("Unauthorized Request");
  }
  return Promise.reject(error);
});

Share on social media

//