How to use request interceptors and response interceptors in Axios

Axios is a commonly used JavaScript library for sending HTTP requests and handling responses. In website design, we can use Axios request interceptor and response interceptor to achieve some common requirements, such as adding authentication information, handling error messages, etc. Here is a simple example:

import axios from 'axios';

// 创建一个 Axios 实例
const instance = axios.create({
  baseURL: 'https://xxx.example.com',
  timeout: 5000,
});

// 添加请求拦截器
instance.interceptors.request.use(
  function(config) {
    // 在请求发送之前做一些自定义操作
    config.headers.Authorization = 'Bearer ' + localStorage.getItem('token');
    return config;
  },
  function(error) {
    // 对请求错误做些什么
    return Promise.reject(error);
  }
);

// 添加响应拦截器
instance.interceptors.response.use(
  function(response) {
    // 对响应数据做些什么
    return response.data;
  },
  function(error) {
    // 对响应错误做些什么
    if (error.response.status === 401) {
      // 处理认证错误
    }
    return Promise.reject(error);
  }
);

// 发送 GET 请求
instance.get('/data').then(function(response) {
  console.log(response);
});

In this example, we first create an Axios instance and use the create method to specify some default configuration, such as the base URL and timeout. Then, we added a request interceptor and a response interceptor.

The request interceptor is added through the use method, where

  • The first function is executed before the request is sent, and the request configuration can be modified here;

  • The second function executes when the request fails.

The response interceptor is also added through the use method, where

  • The first function is executed after receiving the response, where the response data can be processed;

  • The second function is executed when a response error is received, and the error message can be handled here.

Finally, we send the GET request through the instance and process the response data in the then method.

It should be noted that Axios interceptors are called in chains, and each interceptor must return a configuration object or a Promise. The request interceptor can modify the request configuration and return it through return config . The response interceptor can process the response data and return the processed data through return response.data . If an error occurs, the error message can be returned through return Promise.reject(error) , so that the subsequent catch method can catch the error.

Guess you like

Origin blog.csdn.net/chinagaobo/article/details/129571418