The concept of request interceptor and response interceptor

  • Request interceptor: Equivalent to a request detection mechanism, only the request that passes this detection can be sent.
  • Response interceptor: Equivalent to a response detection mechanism, only the response that passes this detection can be returned.

What does a request interceptor do?

  • Request interceptors can add parameters to requests

  • The response interceptor can modify the response so that the client receives the modified response

What is the order of execution of interceptors?

  • The request interceptor is who is at the end of the definition, who intercepts first, and the corresponding interceptor is who defines who intercepts first.

Template code

// Set request interceptor
axios.interceptors.request.use(function (config) {
    console.log("Request interceptor intercept successful number one.");
    config.params = {a: 666666};    
    return config;
    // throw new Error;
}, function (error) {
    console.log("Request interceptor intercept failed # 1.");
    return Promise.reject(error);
});

axios.interceptors.request.use(function (config) {
    console.log("Request interceptor intercept successful number two.");
    return config;
    // throw new Error;
}, function (error) {
    console.log("Request interceptor intercept failed no. 2.");
    return Promise.reject(error);
});
// Set the response interceptor
axios.interceptors.response.use(function (response) {
    console.log("Response interceptor success one.");
    // console.log(response);
    return response.data;
}, function (error) {
    console.log("Response interceptor Default 1");
    return Promise.reject(error);
});

axios.interceptors.response.use(function (response) {
    console.log("Response interceptor success two.");
    return response;
}, function (error) {
    console.log("Response interceptor Default 2");
    return Promise.reject(error);
});

// Use axios to send the request
axios({
    method: 'GET'.url: 'http://localhost:3000/posts'
}).then((response= > {console.log(response)})).catch(reason= > {console.log("Custom callback error"); });Copy the code