axios request interceptor & response interceptor

Posted by devx on Thu, 16 Dec 2021 21:23:48 +0100

1, Interceptor introduction

Generally, when using axios, the interceptor function will be used, which is generally divided into two types: request interceptor and response interceptor.

  1. request interceptor
    Before sending the request, perform necessary operations, such as adding a unified cookie, adding authentication to the request body, setting the request header, etc., which is equivalent to a package of the same operation in each interface;
  2. Response interceptor
    Similarly, the response interceptor has the same function. It only processes the response body after the request is responded, usually unified data processing, and often judges the login failure.

2, Axios instance

  1. Create an axios instance
    // Introducing axios
    import axios from 'axios'
    
    // Create instance
    let instance = axios.create({
        baseURL: 'xxxxxxxxxx',
        timeout: 15000  // millisecond
    })

  2. baseURL settings:
    let baseURL;
    if(process.env.NODE_ENV === 'development') {
        baseURL = 'xxx Local environment xxx';
    } else if(process.env.NODE_ENV === 'production') {
        baseURL = 'xxx production environment  xxx';
    }
    
    // example
    let instance = axios.create({
        baseURL: baseURL,
        ...
    })
  3. Three ways to modify instance configuration
    // The first one has great limitations
    axios.defaults.timeout = 1000;
    axios.defaults.baseURL = 'xxxxx';
    
    // Second: instance configuration
    let instance = axios.create({
        baseURL: 'xxxxx',
        timeout: 1000,  // Timeout, 401
    })
    // Modify after creation
    instance.defaults.timeout = 3000
    
    // The third is to modify the configuration when initiating a request
    instance.get('/xxx',{
        timeout: 5000
    })

    The priorities of these three configuration modification methods are as follows: request configuration > instance configuration > global configuration

3, Configure interceptor

// request interceptor 
instance.interceptors.request.use(req=>{}, err=>{});
// Response interceptor
instance.interceptors.reponse.use(req=>{}, err=>{});

It can be seen from the above that instance is still the instance created in the second step, and then intercept it. The request uses request and responds to the application reply. Both have two configuration items, one is successful configuration and the other is error configuration.

  1. request interceptor
    // Use (two parameters)
    axios.interceptors.request.use(req => {
        // What to do before sending a request
        ...
        return req
    }, err => {
        // What to do when the request is wrong
        ...
        // The returned data is Axios Data received in catch (ERR)
        return Promise.reject(err)
    })

  2. Response interceptor
    // Use (two parameters)
    axios.interceptors.reponse.use(res => {
        // The request succeeded in processing the response data
        ...
        // The returned data is Axios Data received in then (RES)
        return res
    }, err => {
        // What to do when the request is wrong
        ...
        // The returned data is Axios Data received in catch (ERR)
        return Promise.reject(err)
    })

  3. Common error code handling (error)
    When axios requests an error, you can handle the error in catch.
    axios.get().then().catch(err => {
        // error handling
    })

    However, in the actual development process, error handling is generally done uniformly in the request / response interceptor, and separate catch error handling is done if there is a special interface

4, Case of axios request interceptor

 

Before sending the axios request, intercept the request and add the csrftoken value obtained from the cookie to the request. To solve the csrf verification problem of the back-end interface.

As follows, you can create a new axios in the src directory of the vue project_ instance. JS file, which is used to create an axios instance and configure it.

import axios from 'axios'

// Create an axios instance
const axios_instance = axios.create()

// Set axios Interceptor: request interceptor
axios_instance.interceptors.request.use(config => {
  //What are the general operations of request interception
  // 1. For example, some information in config does not meet the requirements of the server. You can modify it here
  // 2. For example, every time you send a network request, you want to display a request icon in the interface (and then cancel the display in response interception)
  // 3. Some network requests must carry some special information (such as login token). If they are not carried, they can be intercepted and prompted

  // Add a token to the request header
  /*
  * Of which /* csrftoken=([^;.]*).*$/     Is a regular expression used to obtain the value of csrftoken from the cookie,
  * ([^;.]*) Is a named capture, which means that only the values in () are obtained from the matched content.
  * string.match(regex) What you get is an array. Item 0 is all the matched contents, and item 1 is the contents obtained through naming capture. Here is the value of csrftoken.
  * This completes the correct configuration of sending requests using axios, and ensures that the website is free from csrf attacks
  */
  config.headers['X-Requested-With'] = 'XMLHttpRequest';
  let regex = /.*csrftoken=([^;.]*).*$/; // Used to match the csrftoken value from the cookie
  config.headers['X-CSRFToken'] = document.cookie.match(regex) === null ? null : document.cookie.match(regex)[1];
  return config
}, err => {
  // The request was not sent successfully, such as: no network
  return Promise.reject(err)
})

/*
// Set axios Interceptor: response interceptor
axios_instance.interceptors.response.use(res => {
  // Interception of successful response
  return Promise.resolve(res.data)
}, err =>{
  // Interception of failed responses
  console.log(err)
  if(err.response){
    // The status of the failed response needs to be obtained in the response
    console.log(err.response)
    switch(err.response.status){
      // The processing of the obtained status code depends on your own situation
      case 401:
          console.log('Not logged in ')
          window.location.href='/'
          break
      case 404:
          window.location.href='/'
          break
      case 405:
          console.log('Unsupported method ')
          break
      // case ...
      default:
          console.log('Other errors')
          break
    }
  }
  // Note that you should return promise here reject(),
  // If you return err directly, if the response fails when calling this instance, it will also enter then (RES = > {}) instead of reject or catch methods
  return Promise.reject(err)
})
*/


export {
  axios_instance
}

So,
Where the request or response needs to be intercepted, the newly created axios instance can be used to initiate asynchronous requests;
Instead of intercepting requests / responses, you can directly use axios to initiate asynchronous requests!!!

Topics: Java Vue Vue.js