How to use Axios interceptor

Time:2021-1-27

Sometimes we need to process the requests sent by Axios uniformly. Here we need to use interceptors

  • First, create an Axios example
    import axios from 'axios'
    const $http = axios.create({
      baseURL: '/api/',
      timeout: 5000 // request timeout
    })
  • Request interceptor, inBefore the request is initiatedInterception processing
    //HTTP response interceptor
    $http.interceptors.response.use(
      config => {
          //Intercept the request and do unified processing
          console.log ('data to be requested ');
          console.log(config);
          return config
      },
      error => {
      return Promise.reject(error) 
    })
  • Response interceptor, after the interface returns dataBefore response processingInterception processing
    //HTTP response interceptor
    $http.interceptors.response.use(
      response => {
          //Intercept response and do unified processing
          console.log ('data request succeeded ');
          console.log(response);
          const res = response.data
          return res
      },
      //Interface error state handling, that is, handling when there is no response
      error => {
      return  Promise.reject ( error.response.status )// returns the error information returned by the interface
    })
  • After that, you can expose the Axios example and use it normally
    export default $http

This work adoptsCC agreementReprint must indicate the author and the link of this article

Recommended Today

Practice of query operation of database table (Experiment 3)

Following the previous two experiments, this experiment is to master the use of select statements for various query operations: single table query, multi table connection and query, nested query, set query, to consolidate the database query operation.Now follow Xiaobian to practice together!Based on the data table (student, course, SC, teacher, TC) created and inserted in […]