Introduction to axios and notes on source code analysis

Keywords: Front-end JSON

1, JSON server

  1. Official website document address
    JSON server document
  1. Install JSON server
    npm install -g json-server
  1. Create a database JSON file under the target root directory: db.json
	{
	"posts": [
	  { "id": 1, "title": "json-server", "author": "typicode" }
	],
	"comments": [
	  { "id": 1, "body": "some comment", "postId": 1 }
	],
	"profile": { "name": "typicode" }
	}
  1. Start JSON server
    Enter the following command in the current folder: JSON server db.json

2, Understanding and use of axios

1. What is Axios?

  1. The most popular ajax request library on the front end
  2. react/vue officials recommend using axios to send ajax requests
  3. file: https://github.com/axios/axios

2.axios features

  1. Asynchronous ajax request Library Based on xhr + promise
  2. Both browser side and node side can be used
  3. Support request / response interceptors
  4. Support request cancelled
  5. Request / response data conversion
  6. Batch send multiple requests

3. axios common syntax

  1. axios(config): a general / essential way to send any type of request
  2. axios(url[, config]): you can only specify the url to send a get request
  3. axios.request(config): equivalent to axios(config)
  4. axios.get(url[, config]): send get request
  5. axios.delete(url[, config]): Send a delete request
  6. axios.post(url[, data, config]): Send a post request
  7. axios.put(url[, data, config]): Send a put request
  8. axios.defaults.xxx: requested default global configuration
  9. axios.interceptors.request.use(): add request interceptor
  10. axios.interceptors.response.use(): add a response interceptor
  11. axios.create([config]): create a new Axios (it does not have the following functions)
  12. axios.Cancel(): error object used to create cancel request
  13. axios.CancelToken(): a token object used to create cancellation requests
  14. axios.isCancel(): is it an error to cancel the request
  15. axios.all(promises): used for batch execution of multiple asynchronous requests
  16. axios.spread(): used to specify the method of callback function to receive all successful data

4. Use of Axios - default configuration

1. Basic use

	// Introduce bootstrap style
	<link
      crossorigin="anonymous"
      href="https://cdn.bootcss.com/twitter-bootstrap/3.3.7/css/bootstrap.min.css"
      rel="stylesheet"
    />
	<div class="container">
      <h2 class="page-header">Basic use</h2>
      <button class="btn btn-primary">send out GET request</button>
      <button class="btn btn-warning">send out POST request</button>
      <button class="btn btn-success">send out PUT request</button>
      <button class="btn btn-danger">send out DELETE request</button>
    </div>
	// Introducing axios
	<script src="https://cdn.bootcdn.net/ajax/libs/axios/0.21.1/axios.min.js"></script>
	<script>
      //Get button
      const btns = document.querySelectorAll('button')

      //first
      btns[0].onclick = function () {
        //Send AJAX request
        axios({
          //Request type
          method: 'GET',
          //URL
          url: 'http://localhost:3000/posts/2'
        }).then((response) => {
          console.log(response)
        })
      }

      //Add a new article
      btns[1].onclick = function () {
        //Send AJAX request
        axios({
          //Request type
          method: 'POST',
          //URL
          url: 'http://localhost:3000/posts',
          //Set request body
          data: {
            title: 'it's a nice day today, It's quite sunny',
            author: 'Zhang San'
          }
        }).then((response) => {
          console.log(response)
        })
      }

      //Update data
      btns[2].onclick = function () {
        //Send AJAX request
        axios({
          //Request type
          method: 'PUT',
          //URL
          url: 'http://localhost:3000/posts/3',
          //Set request body
          data: {
            title: 'it's a nice day today, It's quite sunny',
            author: 'Li Si'
          }
        }).then((response) => {
          console.log(response)
        })
      }

      //Delete data
      btns[3].onclick = function () {
        //Send AJAX request
        axios({
          //Request type
          method: 'delete',
          //URL
          url: 'http://localhost:3000/posts/3'
        }).then((response) => {
          console.log(response)
        })
      }
    </script>

2. Default configuration

//Default configuration
       axios.defaults.method = 'GET';//Set the default request type to GET
       axios.defaults.baseURL = 'http://localhost:3000';// Set base URL
       axios.defaults.params = {id:100};
       axios.defaults.timeout = 3000;//

       btns[0].onclick = function(){
           axios({
               url: '/posts'
           }).then(response => {
               console.log(response);
           })
       }

5. Schematic diagram

6. Understanding and use of difficult grammar

1,axios.create(config)

  1. Create a new axios according to the specified configuration, that is, each new axios has its own configuration

  2. The new axios just doesn't have the method of canceling requests and sending requests in batches. All other syntax is the same

  3. Why design this grammar?

(1) Requirements: the configuration required by some interfaces in the project is different from that required by other interfaces. How to deal with it

(2) Solution: create two new axios, each with its own unique configuration, which are applied to interface requests with different requirements

 //Create instance object / getJoke
   const duanzi = axios.create({
     baseURL: 'https://api.apiopen.top',
     timeout: 2000
   });
   const onather = axios.create({
     baseURL: 'https://b.com',
     timeout: 2000
   });
   //Here, the functions of duanzi and axios objects are almost the same
   // duanzi({
   //     url: '/getJoke',
   // }).then(response => {
   //     console.log(response);
   // });
   duanzi.get('/getJoke').then(response => {
     console.log(response.data)
   })

2. Interceptor function / ajax request / call order of callback function of request

  1. Note: calling axios() does not send ajax requests immediately, but requires a long process
  2. Process: request interceptor 2 = > request interceptor 1 = > send ajax request = > response interceptor 1 = > response interceptor 2 = > callback of request
  3. Note: this process is connected in series through promise. The request interceptor passes config and the response interceptor passes response
 <script>
   // Promise
   // Set request interceptor config configuration object
   axios.interceptors.request.use(function (config) {
     console.log('Request interceptor succeeded - 1 number');
     //Modify parameters in config
     config.params = {
       a: 100
     };

     return config;
   }, function (error) {
     console.log('Request interceptor failed - 1 number');
     return Promise.reject(error);
   });

   axios.interceptors.request.use(function (config) {
     console.log('Request interceptor succeeded - 2 number');
     //Modify parameters in config
     config.timeout = 2000;
     return config;
   }, function (error) {
     console.log('Request interceptor failed - 2 number');
     return Promise.reject(error);
   });

   // Set response interceptor
   axios.interceptors.response.use(function (response) {
     console.log('Response interceptor success No. 1');
     return response.data;
     // return response;
   }, function (error) {
     console.log('Response interceptor failed No. 1')
     return Promise.reject(error);
   });

   axios.interceptors.response.use(function (response) {
     console.log('Response interceptor success No. 2')
     return response;
   }, function (error) {
     console.log('Response interceptor failed No. 2')
     return Promise.reject(error);
   });

   //Send request
   axios({
     method: 'GET',
     url: 'http://localhost:3000/posts'
   }).then(response => {
     console.log('Results of successful processing of custom callback');
     console.log(response);
   });
 </script>

3. Cancel request

  1. Basic process configuration cancelToken object
  2. Cache the cancel function used to cancel the request
  3. Call the cancel function at a later specific time to cancel the request
  4. Judge in the error callback that if the error is cancel, handle it accordingly
  5. To realize the function, click the button to cancel a request in progress,
 <script>
   //Get button
   const btns = document.querySelectorAll('button');
   //2. Declare global variables
   let cancel = null;
   //Send request
   btns[0].onclick = function () {
     //Check whether the last request has been completed
     if (cancel !== null) {
       //Cancel last request
       cancel();
     }
     axios({
       method: 'GET',
       url: 'http://localhost:3000/posts',
       //1. Add the properties of the configuration object
       cancelToken: new axios.CancelToken(function (c) {
         //3. Assign the value of c to cancel
         cancel = c;
       })
     }).then(response => {
       console.log(response);
       //Initialize the value of cancel
       cancel = null;
     })
   }

   //Bind second event cancel request
   btns[1].onclick = function () {cancel(); }
 </script>

3, axios source code and analysis

1. Difficult problems of Axios

1. Directory structure

/ dist / # project output directory
/ lib / # project source directory
│ ♪ - / adapters / # define the requested adapter xhr, http
│ │♪ -- http.js # implements HTTP adapter (wrapping HTTP package)
│ │ └ - xhr.js # implement XHR adapter (wrap XHR object)
│ ♪ - / cancel / # define cancel function
│♪ - / core / # some core functions
│ │♪ - core main class of Axios.js # axios
│ │♪ -- dispatchRequest.js # is a function used to call the http request adapter method to send a request
│ │♪ - manager of InterceptorManager.js # interceptor
│ │ └ -- set.js # changes Promise status according to http response status
│♪ - / helpers / # some auxiliary methods
│♪ - axios.js # external exposure interface
│♪ - default configuration of defaults.js # axios
│ └ - utils.js # utility
package.json # project information
index.d.ts # configures the declaration file of TypeScript
└ - index.js # entry file

2. Relationship between Axios and Axios

  1. Syntactically, Axios is not an instance of Axios
  2. Functionally, Axios is an instance of Axios
  3. axios is the function returned by the Axios.prototype.request function bind()
  4. As an object, Axios has all methods on the Axios prototype object and all properties on the Axios object

3. What is the difference between instance and axios?

  1. Same:
    (1) Is a function that can send any request: request(config)
    (2) There are various methods for making specific requests: get()/post()/put()/delete()
    (3) Both have default configuration and interceptor properties: defaults/interceptors
  2. Different:
    (1) The default configuration is likely to be different
    (2) instance does not have some methods added after axios: create()/CancelToken()/all()

4. Overall process of Axios operation

  1. Overall process:
    request(config) ===> dispatchRequest(config) ===> xhrAdapter(config)

  2. request(config):
    Connect the request interceptors / dispatchRequest() / response interceptors in series through the promise chain,
    Return promise

  3. dispatchRequest(config):
    Conversion request data = = = > the number of conversion responses after calling xhrAdapter() to send a request = = = > the request returns
    Return promise according to

  4. xhrAdapter(config):
    Create an XHR object, make corresponding settings according to config, send specific requests, and receive response data,
    Return promise

  5. flow chart:

Posted by Fearsoldier on Thu, 28 Oct 2021 19:38:53 -0700