Axios is an HTTP library based on Promise that is used frequently during development, so let’s take a closer look at it

We know that the encapsulation of AXIos is based on Promise and XMLHttpRequests, so we need to do the following prequests:

  • Ajax encapsulation
  • Promise
  • json-server

Ajax encapsulation

Ajax encapsulation is also likely to be asked in the interview process, and many times, we need to understand the principle of the request, so Ajax is divided into four steps:

1. Create asynchronous objects

let xhr = null
// Asynchronous objects need to be compatible with IE6
if(window.XMLHttpRequest){    
    xhr = new XMLHttpRequest()
}else{    
// IE6 asynchronous objects
    xhr = new ActiveXObject('Mricosoft.XMLHTTP')}Copy the code

2. Link server

Get and POST

1. If GET needs to pass parameters, it needs to be concatenated at the end of the URL address bar, but POST does not

Post requires a request header, while GET does not

let url = ' ' // The requested address
let params = { // Parameters sent to the back end
    name:'Joe'
}

/ / the get method
xhr.open('get'.`${url}? name=${params.name}`)

/ / post way
xhr.open('post',url)
xhr.setRequestHeader("Content-Type"."application/x-www-form-urlencoded")Copy the code

3. Send the request

Get and POST

  1. Get passes NULL in send
  2. Post passes objects in send

let params = {
    name:'Joe'
}
/ / the get method
xhr.send(null)

/ / post way
xhr.send(params)Copy the code

4. Receive the requested data

xhr.onreadystatechange = function(){
    // readyState:4 status:200 Indicates that data is returned
    if(xhr.readyState === 4 && xhr.status === 200) {// Get the core text object as the data passed in
        console.log(xhr.responseText)
    }
}Copy the code

Ajax encapsulates the complete code

let options = {
    // Request an address
    url:' '.// Request type
    type:'get/post'.// Parameters to pass
    data:{ 
        name:'Joe'
    },
    success:function(res){
        console.log(res)
    }
}
function ajax(options){
    let xhr = null
    // create an asynchronous object
    if(window.XMLHttpRequest){
        xhr = new XMLHttpRequest()
    }else{
        xhr = new ActiveXObject('Mricosoft.XMLHTTP')}// 2
    if(options.type==='get'){
        xhr.open(options.type,`${options.url}? name=${options.data.name}`)
        xhr.send(null)}else{
        xhr.open(options.type,options.url)
        xhr.setRequestHeader("Content-Type"."application/x-www-form-urlencoded")
        xhr.send(options.data)
    }
    // 3. Receive the requested data
    xhr.onreadystatechange = function(){
        if(xhr.readyState ===4 && xhr.status === 200){
            options.success(xhr.responseText)
        }
    }
}Copy the code

Promise

We will explain the Promise from several questions:

  • What problem was Promise invented to solve?
  • What problems did Promise expose in solving the problem, and how did the Generator solve it?
  • What problem does generator expose, and how does Async fix it?

What problem did Promise come along to solve?

Promise was invented to solve the problem of callback hell, but how does it solve the problem of callback hell? So we need to know that before Promise came along, we used wrapped Ajax to make asynchronous requests. So there’s a problem. Province, city, district, three interfaces, so what will we do, directly on the code, using the ajax we encapsulated above

// Province, city, district
// Request: select province, then send request, select city, then send request, request to district
ajax({ // How many provinces are there in China
    url:' '.type:' '.data:data,
    success:function(res){
        ajax({ // How many cities are there in the province
            url:' '.type:' '.data:data,
            success:function(res){
                ajax({ // How many districts are there in the city
                    url:' '.type:' '.data:data,
                    success:function(res){
                        console.log(res) // The final selected area}})}})Copy the code

Note: This creates what we call callback hell, which is hard to maintain, with layers of nested callbacks

How does Promise solve callback hell? (Here I use setTimeout to simulate the data request)

New Promise(function(resolve,reject){
        setTimeout(function(){
            resolve('province')}, 1000)}). Then (res = > {the console. The log (res) / / request datareturn new Promise(function(resolve,reject){
            setTimeout(function(){
                resolve('the city')}, 1000)})}). Then (res = > {the console. The log (res) / / requests the data againreturn new Promise(function(resolve,reject){
            setTimeout(function(){
                resolve('area')
            },1000)
        })
    }).then(res=>{
        console.log(res)
    })Copy the code

Note that Promise, with its own chain of then, has transformed the triangle callback hell into a vertical structure that is more maintainable.

The problem: The Promise solution to the callback hell problem also exposed the problem of returning a Promise to continue the THEN, which is generator

The advent of the Generator solves the callbacks that Promise introduced

How to solve it?

First, what is a generator function that looks like a normal function except that it ends with function or preceded by *

// Both of the following are generator functions
function* gen(){}
function *gen(){}Copy the code

Second, use it with yield

function *gen(){
    yield new Promise()}Copy the code

Again, examples of provinces, cities and districts

  function* gen() {    
        let res1 = yield Promise.resolve('province')    
        let res2 = yield Promise.resolve('the city')    
        let res3 = yield Promise.resolve('area')}// A variable is required to receive the execution of the generator function
let g = gen() 
/ / need to use the next use, the only provincial data, function stops execution of the console. The log (g.n ext ())Copy the code



The result is an object where done means that the entire generator has not yet finished executing, and if all yield is finished executing, the value is true, and value is a Promise object that gets results from then


After executing the function, change the code

  function* gen() {    
        let res1 = yield Promise.resolve('province')    
        let res2 = yield Promise.resolve('the city')    
        let res3 = yield Promise.resolve('area')}let g = gen()  
    g.next().value.then(res= > {    
        console.log(res)  
    })  
    g.next().value.then(res= > {    
        console.log(res)  
    })  
    g.next().value.then(res= > {    
        console.log(res)  
    })Copy the code

Results:



Again, generator refers to the concept of coroutines, and if you know coroutines, you’re good.

Note that the Generator solves the Promise callback problem, but it also has an obvious problem of its own, requiring next, so async comes into play

Async solves the problem with Generator next

Async should be familiar to everyone, so I will not elaborate too much and use with await

async function asyncFn() {    
        let res1 = await Promise.resolve('province')    
        console.log(res1)    
        let res2 = await Promise.resolve('the city')    
        console.log(res2)    
        let res3 = await Promise.resolve('area')    
        console.log(res3)  
}  
let async = asyncFn()Copy the code

Results:



Note: Obviously async does not need to be next like generator. Async is the syntactic sugar of generator. Async = generator + self-executing functions

json-server

This tool can be used directly as a real request for background data, and can easily change the data, and will be used for subsequent axiOS wrapped debugging

First, install

npm i -g json-serverCopy the code

Create a folder server and create a new file db.json in this folder

// The contents of db.json
{  "data": [{"id": 1."name": "Zhang"."age": "19"    
    },    
    {      
        "id": 2."name": "Bill"."age": "29"}}]Copy the code

Execute the command

json-server --watch --port 53000 db.jsonCopy the code

This is when the service starts



Through http://localhost:53000/data can get the data, and can also modify the data in a json

We use Axios for use case testing

Create a new HTML file and import Axios

<! DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, "> <title>Document</title> </head> <body> <button onclick="getFn()" Onclick ="postFn()">post request </button>< button onclick="putFn()">put request </button></body> <script SRC = "https://cdn.bootcdn.net/ajax/libs/axios/0.19.2/axios.js" > < / script > < script > function getFn () { axios.get('http://localhost:53000/data/') .then(res => { console.log(res) }) } function postFn() { axios.post('http://localhost:53000/data/', { id: 3, name: "Two pock-marked})". Then (res = > {the console. The log (res)})} function putFn () {axios. Put (' http://localhost:53000/data/2 '{name: "Zhao four"}). Then (res = > {the console. The log (res)})} < / script > < / HTML >Copy the code

The style of the page coming out



Let’s say get, Post, put and see what happens, okay

A get request



A post request



Changes to db.json data after POST



Append data to data

Put request



Data changes in db.json after put



The second name of data is changed to “Zhao Si”


So this is the basic use of jSON-server, and we’ll use it later. If you’re interested, check out the other API, JSON-server


Finally: I like to study the interview questions, and I hope to have more like-minded friends to exchange and study together, which can help modify the resume