[Front-end knowledge] Axios - request interceptor template

Axios - request interceptor template

Axios is a Promise-based HTTP client for sending HTTP requests. It can be used in both browser and Node.js environments, and provides many powerful features, such as intercepting requests and responses, transforming request and response data, canceling requests, etc.

Axios has a simple and easy-to-use API that can easily send various types of requests such as GET, POST, PUT, DELETE, etc. It also supports asynchronous operations and concurrent requests.

It is very convenient to use Axios to send HTTP requests. You only need to provide the requested URL and optional configuration parameters, and then Axios will return a Promise object through which you can handle the result of the request.

Axios also supports custom interceptors. You can do some processing before sending a request or after the response is returned, such as setting request headers, verifying response data, error handling, etc.

In general, Axios is a powerful and easy-to-use HTTP client library that is widely used in front-end development and Node.js development.

  • Build status code constants

    /*
     * @Author: outmanchen
     * @Date: 2023-09-06 15:40:56
     * @LastEditors: outmanchen
     * @LastEditTime: 2023-09-06 16:04:37
     * @FilePath: \axios\status.js
     * @Description: 状态码常量
     */
    
    export default {
          
          
    	SUCCESS: 200,
        NOAUTH: 401
        // ...
    }
    
  • Encapsulation interceptor

/*
 * @Author: outmanchen
 * @Date: 2023-09-06 15:37:17
 * @LastEditors: outmanchen
 * @LastEditTime: 2023-09-06 16:05:13
 * @FilePath: \axios\index.js
 * @Description: 网络请求封装
 */
import http from 'axios'; // 引入axios网络请求库
import API from './status'; // 引入状态码常量

/**
 * 请求拦截器
 */
http.interceptors.request.use(function (config) {
    
    
  if(!config.params){
    
    
    config.params = {
    
    };
  }
  // 请求发送前的拦截处理(例如:在headers中添加token、在params中添加时间戳...)
  // ...
  // ...
  return config;
}, function (error) {
    
    
  // 请求发送失败时的处理
  // ...
  // ...
  return Promise.reject(error);
});


/**
 * 响应拦截器
 */
http.interceptors.response.use(function (response) {
    
    
  // 请求响应时的拦截处理(例如:登录鉴权等...)
  // ...
  // ...
  // 登录鉴权-401
  if(response && response.data && response.data.status && response.data.status == API.NOAUTH){
    
    
      // 鉴权逻辑处理
      // ...
      // ...
  }
  return response;
}, function (error) {
    
    
  // 请求响应失败时的处理
  return Promise.reject(error);
});

export default http;

Guess you like

Origin blog.csdn.net/weixin_42919342/article/details/132717812
Recommended