Lesson 04-Axios Request and Response Interceptor Configuration

Request and response interceptors are powerful tools provided by Axios, enabling predefined operations before a request is sent and after a response is received. These operations can include adding headers, processing response data, error handling, logging, authentication, and more.

Request Interceptors

Request interceptors are functions executed before a request is sent to the server. They can modify the request configuration, such as adding authentication tokens, setting headers, or adjusting parameters.

Example Code:

axios.interceptors.request.use(
  function(config) {
    // Perform actions before sending the request
    config.headers['Authorization'] = `Bearer ${localStorage.getItem('token')}`;
    return config;
  },
  function(error) {
    // Handle request errors
    return Promise.reject(error);
  }
);

Response Interceptors

Response interceptors are functions executed before a response is passed to then or catch. They can process response data, such as parsing responses, handling errors uniformly, or executing specific business logic.

Example Code:

axios.interceptors.response.use(
  function(response) {
    // Process response data
    return response;
  },
  function(error) {
    // Handle response errors
    if (error.response.status === 401) {
      // Redirect to login page for unauthorized status
      window.location.href = '/login';
    }
    return Promise.reject(error);
  }
);

Application Analysis

  • Step 1: Define Request Interceptors
    In a request interceptor, you can access the config object and modify its properties, such as adding or updating headers, setting timeouts, etc.
  • Step 2: Define Response Interceptors
    In a response interceptor, you can access the response object to process response data, such as parsing JSON or performing actions based on status codes.
  • Step 3: Error Handling
    In the error handling function of a response interceptor, you can access the error object, which contains detailed error information. You can decide how to handle the error based on its type or status code.

Global Configuration and Default Settings

Axios allows setting global default configurations to simplify code and reduce redundancy. Global configurations apply to all requests unless overridden in individual requests. Common global configuration options include:

  • baseURL: The common URL prefix for all requests.
  • timeout: Request timeout in milliseconds.
  • headers: Default request headers.
  • withCredentials: Whether to include cookies (boolean).
  • adapter: Request adapter for custom request behavior.
  • validateStatus: Function to validate response status.

Global Configuration Example

In your project, you can set global configurations in the entry file (e.g., main.js or index.js) or in a separate configuration file for import where needed.

// axiosConfig.js
import axios from 'axios';

// Set global default configurations
axios.defaults.baseURL = 'https://api.example.com';
axios.defaults.timeout = 5000;
axios.defaults.headers.common['Authorization'] = `Bearer ${localStorage.getItem('token')}`;
axios.defaults.headers.post['Content-Type'] = 'application/json';

// Export axios for use in other modules
export default axios;

Complete Configuration Example

{
  // `url` is the server URL for the request
  url: '/user',

  // `method` is the HTTP method used
  method: 'get', // default

  // `baseURL` is prepended to `url` unless `url` is absolute
  baseURL: 'https://some-domain.com/api/',

  // `transformRequest` allows modifying request data before sending
  // Applies to `PUT`, `POST`, and `PATCH`
  // The last function must return a string, Buffer, ArrayBuffer, FormData, or Stream
  transformRequest: [function (data, headers) {
    // Transform request data
    return data;
  }],

  // `transformResponse` allows modifying response data before passing to then/catch
  transformResponse: [function (data) {
    // Transform response data
    return data;
  }],

  // Custom headers
  headers: {'X-Requested-With': 'XMLHttpRequest'},

  // `params` are URL parameters sent with the request
  // Must be a plain object or URLSearchParams
  params: {
    ID: 12345
  },

  // `paramsSerializer` is an optional function to serialize `params`
  paramsSerializer: function (params) {
    return Qs.stringify(params, {arrayFormat: 'brackets'})
  },

  // `data` is the request body data
  // Applies to `PUT`, `POST`, `DELETE`, and `PATCH`
  // Must be a string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams, FormData, File, Blob, Stream, or Buffer
  data: {
    firstName: 'Fred'
  },

  // Alternative syntax for sending request body data (POST only, sends value only)
  data: 'Country=Brasil&City=Belo Horizonte',

  // `timeout` specifies the request timeout in milliseconds
  timeout: 1000, // default is 0 (no timeout)

  // `withCredentials` indicates whether to send credentials with cross-origin requests
  withCredentials: false, // default

  // `adapter` allows custom request handling for testing
  adapter: function (config) {
    /* ... */
  },

  // `auth` for HTTP Basic Auth
  auth: {
    username: 'janedoe',
    password: 's00pers3cret'
  },

  // `responseType` specifies the data type of the response
  responseType: 'json', // default

  // `responseEncoding` specifies the encoding for decoding responses (Node.js only)
  responseEncoding: 'utf8', // default

  // `xsrfCookieName` is the name of the cookie used for XSRF token
  xsrfCookieName: 'XSRF-TOKEN', // default

  // `xsrfHeaderName` is the HTTP header name for the XSRF token
  xsrfHeaderName: 'X-XSRF-TOKEN', // default

  // `onUploadProgress` handles upload progress events (browser only)
  onUploadProgress: function (progressEvent) {
    // Handle native progress event
  },

  // `onDownloadProgress` handles download progress events (browser only)
  onDownloadProgress: function (progressEvent) {
    // Handle native progress event
  },

  // `maxContentLength` defines the max response content size in bytes (Node.js)
  maxContentLength: 2000,

  // `maxBodyLength` defines the max request body size in bytes (Node.js)
  maxBodyLength: 2000,

  // `validateStatus` determines whether to resolve or reject based on HTTP status
  validateStatus: function (status) {
    return status >= 200 && status < 300; // default
  },

  // `maxRedirects` defines the max number of redirects in Node.js
  maxRedirects: 5, // default

  // `socketPath` specifies a UNIX socket for Node.js
  socketPath: null, // default

  // `httpAgent` and `httpsAgent` define custom agents for HTTP/HTTPS requests in Node.js
  httpAgent: new http.Agent({ keepAlive: true }),
  httpsAgent: new https.Agent({ keepAlive: true }),

  // `proxy` defines the proxy server hostname, port, and protocol
  proxy: {
    protocol: 'https',
    host: '127.0.0.1',
    port: 9000,
    auth: {
      username: 'mikeymike',
      password: 'rapunz3l'
    }
  },

  // `cancelToken` for canceling requests
  cancelToken: new CancelToken(function (cancel) {
  }),

  // `decompress` indicates whether to automatically decompress response body (Node.js only)
  decompress: true // default
}
Share your love