Ajax-axios interceptor

Interceptor role

Mainly to intercept requests between axios requests and responses

There are two types of interceptors:

1. Request interceptor:

        Generally, the token will be added to the request uniformly

2. Corresponding interceptor:

        Generally, the error message will be processed, and the token will be processed when 401 (generally jump to the login page to obtain the token again)

The common processing flow chart of the interceptor is as follows:

The sample code is as follows:

// 添加请求拦截器
axios.interceptors.request.use(function (config) {
    // 在发送请求之前做些什么
    // debugger
    if (localStorage.getItem('token')) {
        config.headers.Authorization = localStorage.getItem('token')
    }
    return config;
    // config 请求报文 请求地址 请求方法 请求头 请求体
}, function (error) {
    // 对请求错误做些什么
    // debugger
    return Promise.reject(error);
});

// 添加响应拦截器
axios.interceptors.response.use(function (response) {
    // 对响应数据做点什么
    // debugger
    return response;
    // response响应报文 
}, function (error) {
    // 对响应错误做点什么
    // debugger
    Toast.fail(error.response.data.message)
    if (error.response.status === 401) {
        location.href = './login.html'
    }
    return Promise.reject(error);
});

1. When the interceptor is requested and executed successfully,

        If the token value is received, append the token to the Authorization of the request header

        (The parameter Authorization is the parameter name required in the interface document)

2. After the corresponding interceptor fails to execute,

        1.2 Use the Toast.fail() method that comes with the common.js file to print the error text in the pop-up box

        The debugger can find the storage location of the prompt text of the error

        2.2 When the token is not obtained/expired, that is, 401

        The debugger can be used to find the specific location where the status code is stored in the error

        If 401, reacquire the user's token by jumping to the login page

Guess you like

Origin blog.csdn.net/weixin_46669844/article/details/127950784