Learn axios must know and be able ~ basic use of axios, must know details before using axios, differences between axios and instance objects, interceptors and cancellation requests


1, Basic usage of axios:

✿ details to know before using axios:

1. The axios function object can be used as an axios(config) function to send a request, or it can be used as an object to call the method axios Request (config)

■ check the source code and find that axios is a function at first, but then add some attributes [method attributes] to it

2. [,] is an optional parameter list, for example: Axios Get (URL [, config]), where [, config] is an optional parameter



✿ the axios function object can call its own axios(config) to send a request, or call the property's method axios Request (config) how to send a request:

<script>
//At first a was just a function
    var a = function () {
        console.log('hi');
    }
    var fn = function () {
        console.log('hi');
    }
    //After adding an attribute to a function object and making its attribute point to a function, a calls its own function or the method of attribute fn - the effect is the same
    a.fn = fn;
    console.log(a);
    console.dir(a);
    a();
    a.fn();
</script>



1. axios(config): call its own, general / essential method to send any type of request:

<button class="btn btn-primary">post request</button>

//Get button
const btns = document.querySelectorAll('button');
btns[0].onclick = function (){
    //Call the axios method to send the AJAx request. The return value of the axios method is a Promise object (the then method can get the result of the asynchronous request)
    axios({
        //Request type
        method: 'post',
        //URL
        url:'http://localhost:3000/posts/2',
	    //Set request body (i.e. transmitted data)
        data:{
  	 	  title: "candy",
   	  	  author: "i like"
        }
    }).then(response => {
        console.log(response)
    })
};

2,axios.request(config): call the method of attribute to send the request, which is equivalent to axios(config)

<button class="btn btn-primary">post request</button>

//Get button
const btns = document.querySelectorAll('button');
btns[0].onclick = function (){
    //Call the axios method to send the AJAx request. The return value of the axios method is a Promise object (the then method can get the result of the asynchronous request)
    axios.request({
        //Request type
        method: 'post',
        //URL
        url:'http://localhost:3000/posts/2',
	    //Set request body (i.e. transmitted data)
        data:{
  	 	  title: "candy",
   	  	  author: "i like"
        }
    }).then(response => {
        console.log(response)
    })
};

3. Use the instance object of axios (created through axios.create([config]):

//Generally, when creating an axios instance, some default configurations are passed in
const instance = axios.create({
baseURL: 'https://some-domain.com/api/',
    timeout: 1000,
    headers: {'X-Custom-Header': 'foobar'}
});
//The instance and axios object functions are basically the same
//Using the instance object instance of axios, the return value of the method is a Promise object (the then method can get the result of asynchronous request)
instance({
    //Request type
    method: 'GET',
    //URL
    url: '/getJoke',
    //Set request body (i.e. transmitted data)
    params:{
       title: "candy",
       author: "i like"
    }
}).then(response => {
    console.log(response);
})



✿ what is the difference between using the axios(config) method and creating an axios instance object?

​ ■ axios.create(config) encapsulates Axios requests and the meaning of creating Axios instance objects: different request interfaces have different configurations. Creating a new Axios instance can have new configurations to meet the interface configuration requirements. Each Axios instance object has its own unique configuration, which is applied to interface requests with different requirements.

​ ■ the axios instance object is basically the same as that of axios, but the instance object lacks the methods of canceling requests and sending requests in batches.



2, Interceptor of axios (preprocessing requests and responses)

1. Request Interceptor: Axios interceptors. request. Use (successful processing function, failed processing function)

■ request interception:

1. Some information in config may not meet the requirements of the server
2. I hope that every time a network request is sent, a request icon can be displayed on the interface, that is, the circle that turns and turns
3. Some network requests must have special information, such as login (a token is required)


2. Response Interceptor: Axios interceptors. response. Use (successful processing function, failed processing function)

■ response interception:

1. Format the response data



3, Cancellation request for axios

■ function: cancel some users, repeatedly click the request button and send requests, causing pressure on the server

■ cancellation method:

(for example, create a cancellation token through a constructor): add the cancelToken attribute to the configuration object, and then get the parameter c (cancellation function) in the execution function

let cancel = null;
//Check whether the last request is completed (if not, cancel the current request)
if(cancle != null){
    cancle();
}
//axios send request
axios.get('/user/12345', {
    cancelToken: new axios.CancelToken(function executor(c){//Parameter C is the cancel function 	 cancel = c;
    })
}).then(response => {
    console.log(response);
    cancel = null; //After the request is executed, restore the initial value of cancel

});

Added by cstevio on Sun, 23 Jan 2022 22:12:14 +0200