Axios instance, Interceptor, Cancel request

  1. Axios creates an instance object to send a request

    Usefulness: The interface data for many projects does not come from a single server. When using the Axios object to send requests to different servers, if the default configuration (protocol, domain name, port, etc.) is made, it can only meet the needs of the first server, and the second server cannot set the default configuration. And Axios can solve this problem by creating instance objects. Different servers use different Axios instance objects, and then set different default configurations.


    Instance objects created by Axios function almost exactly like Axios objects.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    const axios1 = axios.create({ //Axios creates an instance object
    baseURL:'http://localhost:3000',
    timeout: 2000
    });

    axios1({
    url:'/posts',
    }).then(response => {
    console.log(response);
    })

    Instance objects created by Axios can also send requests with encapsulated methods, such as get( ), post( ), request( ), etc.

    1
    2
    3
    Axios1.get('/posts').then(response => {
    console.log(response);
    })


  1. Axios Interceptor

    Interceptors are some functions, which are divided into request interceptor interceptors.request and response interceptor interceptors.response.

    Request Interceptor can use some functions to process and detect the parameters and content of the request, and then send or cancel, similar to a checkpoint.

    Response Interceptor can preprocess the result before processing it. For example, remind/record the failure result, format and process the data result, if there is no problem after processing, it will be handed over to its own callback function for processing, and if there is a problem, the interceptor will handle it by itself. It is also a similar level.


    Request Interceptor and Response Interceptor

    .use( ) has two callbacks for success and failure, the principle is implemented by then( ).

    1
    2
    3
    4
    5
    6
    7
    axios.interceptors.request.use(function(config){ //Set request interceptor
    console.log('request interceptor, success');
    return config;
    }, function(error){
    console.log('request interceptor, failed');
    return Promise. reject(error);
    })
    1
    2
    3
    4
    5
    6
    7
    axios.interceptors.response.use(function(response){ //Set response interceptor
    console.log('response interceptor, success');
    return response;
    }, function(error){
    console.log('Response interceptor, failed');
    return Promise. reject(error);
    })
    1
    2
    3
    4
    5
    6
    7
    8
    axios({ //send request
    method:'GET',
    url: 'http://localhost:3000/posts'
    }).then(response => {
    console.log('custom success result');
    }).catch(reason => {
    console.log('Custom failure callback');
    })

    The result of this code running is ‘request interceptor success’, ‘response interceptor success’, ‘custom success result’. The sequence is to take the successful callback of the request interceptor first, then the successful callback of the response interceptor, and then the successful callback of axios.

    If the request interceptor returns a failure, that is, return Promise.reject() or throw 'there is a problem with the parameter' (Promise syntax), then you cannot go through the successful callback of the response interceptor, and you will go directly to the response The callback of the interceptor failure, and the custom success callback cannot be executed, only the failure callback (such as catch).


    Execution order of multiple request/response interceptors

    If the same axios object has multiple request interceptors and response interceptors, such as:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    axios.interceptors.request.use(function(config){
    console.log('request interceptor, success -1');
    return config;
    });
    axios.interceptors.request.use(function(config){
    console.log('request interceptor, success -2');
    return config;
    });
    axios.interceptors.response.use(function(response){
    console.log('Response interceptor, success -1');
    return response;
    });
    axios.interceptors.response.use(function(response){
    console.log('Response interceptor, success -2');
    return response;
    });
    axios({ //send request
    method:'GET',
    url: 'http://localhost:3000/posts'
    }).then(response => {
    console.log('custom success result');
    })

    The result is ‘request number 2’, ‘request number 1’, ‘response number 1’, ‘response number 2’, ‘custom success result’. That is, the request interceptor is executed first, and the response interceptor is executed first.


    config parameter and response parameter

    config is the configuration object, use config.params = {a:100}; config.timeout = 2000; to configure.

    1
    2
    3
    4
    5
    axios.interceptors.request.use(function(config){
    config.params = {a:100};
    config.timeout = 2000;
    return config;
    });

    response is the response result object, which is actually the response result created by Axios by default (axios.3.6). If you don’t want to process the whole object, but only a part of it, you can return response.data, so that only a specific part is processed. In the following code, the returned result only has the data attribute in the response object, and nothing else.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    axios.interceptors.response.use(function(response){
    return response.data; //Preprocess the returned result in advance
    });
    axios({
    method:'GET',
    url: 'http://localhost:3000/posts'
    }).then(response => {
    console.log(response); //The response here only returns the response.data part of the response result object.
    })


  1. Axios cancel request

    cancelToken: new CancelToken(function (cancel) {}), is an Axios parameter. It takes a function as an argument, and the function has a formal parameter (c) .


    Setting up a cancellation request requires three steps:

    1. Add configuration object properties. cancelToken: new CancelToken(function (cancel) {}) usually takes c as a parameter.
    2. Declare a global variable let cancel = null; to save the function returned by c later.
    3. Assign c to the global variable cancel. cancel = c;
    4. Bind the cancel( ) function in another event to trigger the axios cancellation request of the first event.
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    let cancel = null; //Part 2: Declare global variables

    btns[0].onclick = function(){
    axios({
    method:'GET',
    url:'http://localhost:3000/posts',
    cancelToken: new axios.CancelToken(function(c){ //Step 1: Add properties of the configuration object
    cancel = c; //Step 3: Assign c to the global variable cancel.
    });
    });
    }

    btns[1].onclick = function(){
    cancel(); //Bind the cancel() function in the second event.
    }

    In order to verify the effect, you can add a delay to the server response. In json-server, the way to add delay is to add -d code when starting the server: json-server --watch db.json -d 2000


    The cancel request is often used for anti-shake, that is, when sending a request, first determine whether the previous request is still continuing, and if it continues, cancel it.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    let cancel = null; //Part 2: Declare global variables

    btns[0].onclick = function(){
    if(cancel !== null){cancel();}; //Judge the value of cancel, if it is not null, it means that the last request is not over and needs to be canceled
    axios({
    method:'GET',
    url:'http://localhost:3000/posts',
    cancelToken: new axios.CancelToken(function(c){
    cancel = c;
    });
    }).then(response => {
    console. log(response);
    cancel = null; //Initialize the cancel value
    })
    }

Share