Interview | UHF interview questions of Ajax, fetch, Axios

Time:2021-4-20

Recommended reading address

Nuggets

seekstar

Hello everyone, I’m Lin Yi. The following article is about the UHF interview questions of Ajax, fetch and Axios. Let’s read it together

Mind map

Interview | UHF interview questions of Ajax, fetch, Axios

1、 AJAX

1. Concept

Ajax full name: async JavaScript and XML. XML: is an extensible text markup language, which can extend the user-defined semantic tags. Long ago, XML was used to return data structures from the server, but now it basically returns data in JSON format.

2. Function

Under the condition of not refreshing the whole page, refresh the page locally.

3. Create Ajax in four steps

  1. establishAjaxexample,let xhr = new XMLHttpRequest()IE6 is not compatible with this writing
  2. Open the request, configure the configuration item before the request, with a total of 5 parameters,xhr.open([http method], [url], [async], [userName], [userPass])

    > ` http methods `  There are common request methods, ` post ,  get ,  delete ,  put ,  head ,  options ,  trace ,  connect `。` async ` Represents asynchronous, default is ` true `  Asynchronous, ` false `  It's synchronization. `[ url ]` : was requested by the server ` api `。`[ userName ], [ userPass ]` , which represents the user name and password
    • HTTP methods: delete: delete some data on the server side, usually files. Put: store some content, usually a file, to the server. Head: just get the request header information returned from the server, and do not respond to the content of the main body. Options: generally used to send probing requests to the server to see if the connection is successful
  3. event listeners readystatechangeIn general, the event of Ajax status code change is monitored, which can obtain the main response and request header returned by the server.xhr.onreadystatechange = function (){}, forsynchronizationStep 3 of the Ajax request code to be executed should be placed in thesendIt’s in front of me. Otherwise, it doesn’t make sense.
  4. Send the Ajax request and the Ajax task starts.xhr.send([])XMLHttpRequest.send()Method, if the Ajax request is asynchronous, the method will return after sending the request. If the Ajax request is synchronous, the request must know the response before returning.

    The fifth step is to read the returned dataxhr.responseText

    //1. Create an instance of XMLHttpRequest
    let xhr = XMLHttpRequest()
    //2. Open the connection with the server
    xhr.open('get', 'URL')
    //3. Sending
    xhr.send()
    //4. Receive changes.
    xhr.onreadystatechange = () => {
        if ( xhr . readyState  ==  four &&  xhr . status  ==  two hundred ){   //  readyState :  Ajax status, status: http request status
            console . log ( xhr . responseText );   // Response subject
        }
    }

    4. Ajax status and HTTP status code

  5. There are five Ajax statesxhr.readyState, respectively0, 1, 2, 3, 4

    • Status 0:unsent, just createdXMLHttpRequestInstance has not been sent yet.
    • State 1: (loaded) calledsend()Method, sending request.
    • State 2: (load complete)send()Method execution completed, all response contents have been received
    • State 3:loading, (Interactive) parsing response content
    • State 4:done, indicating that the main content of the response has been parsed and can be called on the client
  • HTTP common status code.

    • 2xx: indicates that the request has been received by the server. Understand, please accept. The common ones are,200OK indicates that the service can return information.204No content. The server processed successfully, but did not return content.
    • 3xxIt is an important high frequency test site,301: indicates permanent transfer. If you return to the old domain name, you will jump to the new domain name.302: temporary transfer. Generally used for server load balancing, but when the number of concurrent servers reaches the maximum, the server will transfer the subsequent users to other servers.307: indicates a temporary redirection.304: indicates that the cache is not set. For files that are not updated frequently, such asCSS / JS / HTML file, the server will combine with the client settings304The loaded resources will be obtained in the client when they are requested next time.
    • 4xx: indicates that the request cannot be understood by the server due to semantic error.400: indicates that the requested parameter is wrong.401: indicates no permission to access.404: indicates that the requested resource does not exist.413: indicates too much interaction with the server.
    • 5xx: server side error.500: indicates an unknown error on the server side.503: server overload.

5. Common properties and methods in AJAX

  1. onabort: indicates what to handle after the request is interrupted. andxhr.abort()Used together.
  2. ontimeout: indicates the timeout of the request and the method of execution. andtimeoutIt is used together with the set events.
  3. response: the main content of the response.
  4. responseText: the specific content of the response is a string, generally a JSON string
  5. responseXML: the specific content of the response is the document.
  6. status: the status code of HTTP.
  7. statusText: status code description
  8. withCredentials: indicates whether cross domain is allowed.
  9. getAllResponseHeaders: get all response header information.
  10. xhr.open(): open URL request.
  11. xhr.send(): means to send Ajax.
  12. setRequestHeader(): set request header. This property must be in thexhr.open()Back.

reflection

  1. postandgetWhat’s the difference?

    httpAll of the request methods can get data and transfer content from the server.get: mainly get data from the server.postIt mainly sends data to the server.
    GETandPOSTIn essence, it isTCPThere is no difference in links. However, due to HTTP regulations and browser / server restrictions, the specific differences are as follows

  2. fromcacheFrom the point of view,getThe request is cached by default by the browser, and thepostBy default, the request will not.
  3. fromparameterFor example,getThe parameters of the request are usually placed in theurlIn the middle,postThe request is placed in the body of the request, sopostThe request is more secure.
  4. fromTCPUp to now,GETProduce aTCPData package;POSTThere are twoTCPData package. For get requests, the browser willhttp headeranddataAnd the server responds to 200 (return data); forPOST, browser sends firstheader, server response100 continue, browser resenddata, the server responds 200 OK (return data). Although the post request needs to be sent twice, there is little difference in time. And not all browsers send packets twice in post,Firefox only sends it once
  5. To think about a problem, find the output

    let xhr = new XMLHttpRequest()
    xhr.open('post', 'api')
    xhr.onreadystatechange = () =>{
        if(xhr.readyState == 2){
            console.log(2)
        }
        if(xhr.readyState == 4){
            console.log(4)
        }
    }
    xhr.send()
    console.log(3)
  6. 3 2 4
    */

    >If you know the concept of task queue, it is not difficult to know the output result. Because it is an asynchronous request, the synchronous main task outputs' 3 'first and' 2,4 'last. If it's up there` xhr.open ('post ','api') '` xhr.open ('post ','api', false) 'and the code is synchronized. Only the output of the main task in the task queue becomes' 2,4,3'.
  7. Let’s think about it again. What is the output of the following code in the synchronization request

    let xhr = new XMLHttpRequest()
    xhr.open('get', 'xxx', false)
    xhr.send()

xhr.onreadystatechange = () => {

console.log(xhr.readyState)

}

>The above result has no output. This involves the knowledge of task queue. The event "onreadystatechange" monitors the change of Ajax status code. The synchronization request above contains` xhr.send () 'after execution, the status code of Ajax has changed from 0 to 4, and it has not been executed to the listening event' onreadystatechange ', so there is no output result. If the listening event is placed in the` xhr.send Before () ', then the output is 4.

#2、 Axios
>'Axios' is' Ajax' encapsulated by 'promise'. Axios is not a class, it's a method.

##1. Axios attribute
>Axios has' get, post, put, patch, delete 'and other request methods. All instances returned by' get, post 'are' promise ', so you can use the' promise 'method. The basic practical methods are given below.
* ` axios.get () ', send a' get 'request to the server.

axios.get(‘apiURL’, {

param: {
    id: 1
}

}).then(res=>{

console.log(res);

})
.catch( error=>{

console.log(error)

}

>The key value pairs in 'param' will eventually be spliced to the requested link in the form of '?', and sent to the server.
* ` axios.post () 'examples

axios.post(‘apiURL’,{

User: 'Lin Yi',
    age: 18

}).then( res=>{

console.log(res);

})
.catch( error=>{

console.log(error)

}

* ` axios.put () 'examples

axios.put(‘apiURL’, {

Name: 'Lin Yi',

})

* ` axios.patch (URL [, data [, config]])

axios.patch(‘apiURL’, {

id: 13,

},{
timeout: 1000,
})

* ` axios.delete () 'examples

axios.delete(‘apiURL’, {

params: {
    id: 1
},
timeout: 1000

})

##2. A concurrent request` axios.all ([])`
> ` axios.all () multiple requests can be implemented, and all requests need to be completed before doing something.

let requestArr = [axios.get(‘apiURL/1’), axios.get(‘apiURL/2’), axios.post(‘apiURL/3’, {id: 3})]
axios.all(requestArr).then(res => {

console.log(res)

})

###  Thinking, Axios . all ()  How to implement concurrent requests?
> ` axios.all () 'using` promise.all () 'implementation, take a look at the source code in Axios

axios.all = function all(promises) {

return Promise.all(promises);

};

##  three .  Configuration items in Axios.
>Practical [Axios configuration item]( http://www.axios-js.com/zh-cn/docs/index.html# %E9%85%8D%E7%BD%AE%E9%BB%98%E8%AE%A4%E5%80%BC)

#3、 Fetch
##1. Introduce fetch
*'fetch': it is a data request method of 'HTTP'. It is an alternative to 'XMLHttpRequest'. It does not use the 'XMLHttpRequest' class. `Fetch ` is not Ajax, but native JS. `Fetch() 'uses' promise', not a callback function. `Fetch 'is a new API in es8, and its compatibility is not very good. Ie is completely incompatible with the' fetch 'writing method.
*The 'fetch ()' is designed in a modular way, and the APIs are distributed on the 'response' object, the 'request' object, and the 'headers' object.
*  ` fetch ()`  Processing data through data stream (stream object) is very useful for the scene of requesting large files or slow network speed. ` XMLHttpRequest `  No data stream is used. All requests must be completed before they are received
*By default, 'fetch' will not accept or send 'cookies`

##  two .  fetch ( url ,  optionObj )  Basic use
*  Receive the first parameter of the request ` url ` The default request method is ` get `。
*The second is the optional parameter 'optionobj', which can control the properties of different configurations. For example, the 'method:' property is a string. `Headers': an object that can set the HTTP request header. `Body ': the data body of the' post 'request, and the attribute is also a string. `"Credentials" indicates whether 'cookies' can be carried, and "includes" indicates whether' cookies' are included in the same source.
* ` fetch `  The parameter is not set synchronously because ` fetch `  It's based on ` promise `  Encapsulation itself is asynchronous.
*Although 'fetch' is encapsulated by 'promise', the 'catch' function can't catch errors directly, so some operations need to be done in the first 'then' function.
> ` fetch `  When a post request is sent, when a cross domain request occurs, ` fetch `  One will be sent first ` OPTIONS `  Request to confirm whether the server is allowed to accept the request. This request is mainly used to ask whether the server is allowed to modify the header and other operations. After the server agrees, it returns 204 before sending the real request. Two requests will not be generated without cross domain.

__ A get request__

const pro = fetch(‘https://lyypro.gitee.io/blog/’)
pro.then( response =>

response.json()

).catch( err => {

console.log(err)

})

__ A post request__

const URL = ‘https://lyypro.gitee.io/blog/’
const init = {

method: 'POST',
header: {
    "Content-type": "application/x-www-form-urlencoded; charset=UTF-8",
},
Data: 'id = 12 & name = Lin Yi',
credentials: 'include'

}
const pro = fetch(URL, init)
pro.then( response =>

response.json()

).catch( err => {

console.log(err)

})

>The above requests can be modified by using 'await, async', which is not shown here. At the same time, in the 'post' request, the 'data' attribute only supports strings, which we can use

##4. Three modules of fetch
* ` Response `  modular: ` fetch `  After the request is sent, it will get a response from the server ` response ` This response is a response to http.
*'request 'module: This is the module used for the request server. The' data, header and method 'mentioned above are all attributes of the' request 'module.
*'heads', this is a` Response.headers `The properties on are used to manipulate the information of the response header.
>For the detailed properties of the above three, please refer to [teacher Ruan's fetch API tutorial]( http://www.ruanyifeng.com/blog/2020/12/fetch-tutorial.html )

##5. Think about the reasons for sending post twice
>When using 'fetch' to send a 'post' request, if it is cross domain, then 'fetch' will send an 'options' request for the first time, asking whether the server supports the modified request header. If the server supports it, the real request will be sent for the second time.

##  six . Think about the shortcomings of fetch
>1. The 'get / head' request of 'fetch' cannot set the 'body' property.
>  two . ` fetch `  After the request, the server returns the status code no matter how many ( 4xx ,  5xx ) , ` fetch `  They don't think it's a failure, that is to say, using ` catch `  We can't catch the error directly, so we need the first one ` then `  Do something about it.

##4、 Interview questions
>Encapsulating native Ajax
###1. Implement an Ajax.
>Encapsulating native Ajax as promise

var myNewAjax = function (url) {

return new Promise(function (resolve, reject) {
    var xhr = new XMLHttpRequest();
    xhr.open('get', url);
    xhr.send(data);
    xhr.onreadystatechange = function () {
        if (xhr.status == 200 && readyState == 4) {
            var json = JSON.parse(xhr.responseText);
            resolve(json)
        } else if (xhr.readyState == 4 && xhr.status != 200) {
            reject('error');
        }
    }
})

}

###  two .  How many states does Ajax have? What do they represent?
>  Ajax five states look up.

###3. Differences between fetch vs Ajax vs Axios
*The traditional 'Ajax' uses the 'XMLHttpRequest' object to interact with the back end. `JQuery Ajax 'encapsulates the native' XHR '. If there is a check-in between multiple requests, there will be a callback problem.
*Axios uses promise to encapsulate XHR, which solves the problem of callback hell
*'fetch' is not 'XMLHttpRequest','fetch 'is a native JS and uses' promise'.

###What are the advantages of fetch over Ajax?
>Fetch uses promise, which is convenient to use asynchronously, without the problem of callback hell.

###5. How to implement an Ajax request? What do I need to do if I want to issue two sequential Ajax?
>The request to implement AJAX is the above step to create Ajax. To achieve two sequential Ajax, you can use` promise.then ()`

###6. How to solve the browser cache problem with Ajax
*Set the request header and add the` anyAjaxObj.setRequestHeader ("if modified since", "0") 'or` anyAjaxObj.setRequestHeader ("Cache-Control","no-cache")`。
*Add a random number after the URL: '"fresh ="+ Math.random ()`。  Or add "nowttime =" + new date(). Gettime() "after it.
*If you are using jQuery, you can do it directly '$. Ajaxsetup ({ cache:false })`。 In this way, all Ajax on the T side of the page will execute this statement, but there is no need to save the cache record.

#5、 Reference
[the difference between get and post]( https://www.oschina.net/news/77354/http-get-post-different )

[ Fetch API tutorial ]( http :// www . ruanyifeng . com / blog / two thousand and twenty / twelve / fetch - tutorial . html )

[MDN XMLHttpRequest](https://developer.mozilla.org/zh-CN/docs/Web/API/XMLHttpRequest)

[MDN fetch](https://developer.mozilla.org/zh-CN/docs/Web/API/Fetch_API/Using_Fetch)

#6、 It's over
> __ Thank you for reading here. If this article can inspire or help you, welcome [star]( https://github.com/lurenacm/againJS/issues )I'm Lin Yi. See you next time__

Recommended Today

Analysis of super comprehensive MySQL statement locking (Part 1)

A series of articles: Analysis of super comprehensive MySQL statement locking (Part 1) Analysis of super comprehensive MySQL statement locking (Part 2) Analysis of super comprehensive MySQL statement locking (Part 2) Preparation in advance Build a system to store heroes of the Three KingdomsheroTable: CREATE TABLE hero ( number INT, name VARCHAR(100), country varchar(100), PRIMARY […]