Recommended Reading Address

The Denver nuggets

ostar

Hello everyone, I’m Lin Yiyi. The following article is about Ajax, Fetch, Axios UHF interview questions. Read it together 🤗

Mind mapping

A, Ajax

1. The concept

AJAX: Async JavaScript and XML. XML: An extensible text markup language that extends custom semantic tags. Long ago, XML was used to return data structures from the server, and now it’s mostly JSON format.

2. The role

Refresh the page locally without refreshing the global.

3. Four steps to creating Ajax

  1. createAjaxInstance,let xhr = new XMLHttpRequest(), IE6 is not compatible with this notation
  2. Xhr. open([HTTP method], [url], [async], [userName], [userPass])

    > 'HTTP methods' have common request methods are,' POST, GET, DELETE, PUT, HEAD, OPTIONS, TRACE, CONNECT '. 'async' stands for async. Default is' true 'async and' false 'is synchronous. '[url]' : is the 'API' that wants the server to request. '[userName], [userPass]', represents the userName and password
    • HTTP Methods: Delete: Delete some data on the server side, usually a file. PUT: puts something, usually a file, to the server, and HEAD: just gets the request header information returned from the server, not the body content. Options: usually used to send a probing request to the server to see if the connection was successful
  3. Event listenersreadystatechange, generally listens for Ajax status code change events, this event can get the response master and request header returned by the server.xhr.onreadystatechange = function (){}forsynchronousStep 3 of the Ajax request code to perform is put insendIn front of. Otherwise it doesn’t make sense.
  4. The Ajax request is sent, and the Ajax task begins execution. Send ([]), the XMLHttpRequest.send() method that sends the request and returns it if the Ajax request is asynchronous, or if the Ajax request is synchronous, the request must know the response before it returns.

    The fifth step, if you count it, is to read the returned data
    xhr.responseText 。

    Let XHR = XMLHttpRequest() // 2. Xhr. open('get', 'URL') // 3 Send xhr.send() // 4. Receive changes. xhr.onreadystatechange = () => { if(xhr.readyState == 4 && xhr.status == 200){ // readyState: Ajax status, status: HTTP request status console.log(xhr.responseText); // Response body}}

    4. Ajax status and HTTP status codes

  5. There are five Xhr. readyStates for Ajax states: 0, 1, 2, 3, and 4

    • State 0:unsent, just createdXMLHttpRequestInstance, not sent yet.
    • State 1 :(load) calledsend()Method is sending a request.
    • State 2 :(Loaded completed)send()Method execution completes and all responses have been received
    • Condition 3:loading, (interaction) is parsing the response content
    • Condition 4:done, indicating that the body content of the response has been parsed and can be invoked on the client side
  • A common HTTP status code.

    • 2xx: Indicates that the request has been received by the server. Understanded.Please accept. The common ones are,200OK means that the service is able to return information.204No Content. The server processed successfully, but no content was returned.
    • 3xx: a class of important high-frequency test points,301: indicates permanent transfer, return to the old domain will jump to the heart domain.302: Temporary transfer. Generally used for server load balancing, but when the number of concurrency of the server reaches the maximum, the server will transfer the subsequent users to other servers.307: Represents a temporary redirect.304: Indicates that cache is not set, for files that are not updated frequently, for exampleThe CSS/js/HTML files, the server will combine the client Settings304State in which the loaded resource will be retrieved from the client the next time it is requested.
    • 4xxThe request cannot be understood by the server side.400: Indicates that the request parameter is wrong.401: indicates access without permission.404: The requested resource does not exist.413: Indicates that the interaction with the server is too large.
    • 5xx: Server side error.500: Indicates an unknown error on the server side.503: Server overloaded.

5. Common properties and methods used in Ajax

  1. onabort: Indicates what to do after the request is interrupted. andxhr.abort()Use them together.
  2. ontimeout: Represents the timeout of the request and the execution method. andtimeoutSet events to be used together.
  3. response: The body of the response.
  4. responseText: The specific content of the response is a string, usually a JSON string
  5. responseXML: The concrete content of the response is the document.
  6. status: HTTP status code.
  7. statusText: Status code description
  8. withCredentials: Indicates whether cross-domain is allowed.
  9. getAllResponseHeaders: Gets all response headers.
  10. xhr.open(): Opens the URL request.
  11. xhr.send(): means to send Ajax.
  12. setRequestHeader(): Sets the request header. This property must be inxhr.open()behind

thinking

  1. What’s the difference between post and get?

    httpData can be retrieved from the server and content can be delivered in all of the request methods.
    get: Mainly retrieves data from the server.
    postIt mainly sends data to the server.


    GET 和
    POSTIt’s essentially
    TCPLinks are not different, but due to HTTP regulations and browser/server restrictions specific differences are as follows

  2. fromThe cacheIn terms of,getThe request will be cached by the browser by default, andpostThe request default is not.
  3. fromparameterSpeaking,getThe parameters of the request are usually placed inurl,postThe request is placed in the request body, sopostRequest more security.
  4. fromTCPSpeaking,GETTo produce aTCPPackets;POSTProduce twoTCPPackets. For GET requests, the browser will sendhttp headeranddataSend along, the server responds with 200 (return data); And forPOST, the browser sends it firstheader, server response100 continue, the browser sends it againdata, the server responds with 200 OK (return data). Although POST requests need 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. Let’s think about a problem and 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 the task queue, it is not difficult to know the output result, because it is an asynchronous request, so the synchronous main task first output '3', and finally output '2', 4 '. If 'xhr.open('post',' API ') 'above changes to' xhr.open('post', 'API ', false) ', the code will be synchronized, and only the main task in the task queue will output' 2, 4, 3 '.
  7. One more question to think about, what is the output of the following code in a synchronization request

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

xhr.onreadystatechange = () => {

console.log(xhr.readyState)

}

The result above > is nothing. This is related to the knowledge of the task queue. The 'onreadystatechange' event listens for Ajax status code changes. In the above synchronous request, 'xhr.send()' has been executed, and the Ajax status code has changed from 0 to 4. It has not been executed to the 'onreadystatechange' listener event, so there is no output result. If you put the listening event before 'xhr.send()', then the output is 4. Axios > 'Axios' is' ajax' wrapped with 'promise'. Axios is not a class, it's a method. Axios has requests for 'get', 'post', 'put', 'patch', 'delete', etc. All instances returned by 'get' and 'post' are 'promises', so you can use the' promise 'method. The basic practical method is given below. * 'axios. Get ()' sends 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 '? 'in the form of splicing the request onto the link and sending it to the server. * ` axios. Post () ` example

axios.post(‘apiURL’,{

User: 'Lin Yiyi ', age: 18

}).then( res=>{

console.log(res);

})

.catch( error=>{

console.log(error)

}

* ` axios. The put () ` example

axios.put(‘apiURL’, {

Name: 'Lin Yiyi ',

})

* 'axios. Patch (url[, data[, config]])

axios.patch(‘apiURL’, {

id: 13,

},{

timeout: 1000,

})

* ` axios. Delete () ` example

axios.delete(‘apiURL’, {

params: {
    id: 1
},
timeout: 1000

})

## 2. A concurrent request 'axios.all([])' > 'axios.all()' can implement multiple requests that 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)

})

How does Axios.all () implement concurrent requests? > 'axios. All ()' uses the 'promise.all()' implementation. Check out the Axios source

axios.all = function all(promises) {

return Promise.all(promises);

};

## 3. Configuration items in Axios. > utility [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. Fetch * 'Fetch' : Fetch is an alternative to 'XMLHttpRequest', which does not use the class 'XMLHttpRequest'. 'Fetch' is not Ajax, it's native JS. 'fetch()' uses' Promise 'and does not use callbacks. 'FETCH' is a new API in ES8. Its compatibility is not very good. IE is completely incompatible with 'FETCH' writing. * 'fetch()' adopts modular design, and the API is scattered on 'Response' object, 'Request' object and 'Headers' object. * 'fetch()' handles data through a Stream object. This is useful for scenarios where large files are requested or the network speed is slow. 'XMLHttpRequest' does not use a data stream, All requests must be completed before they are fetched. * By default 'fetch' does not accept or send 'cookies' ## 2. The fetch(url, optionObj) basically uses * to receive the' url 'of the request with the first parameter, the default request is' get'. * The second is the optional 'optionObj' parameter, which controls the properties of different configurations. For example, the 'method:' property is a string. 'headers' : An object that sets the headers of HTTP requests. 'body' : 'POST' request of the data body, attributes are also a string. 'Credentials' means whether' cookies' can be carried, and 'includes' means whether' cookies' are included in the same family. * The 'fetch' parameter has no synchronous setting because 'fetch' is based on 'promise' encapsulation and is itself asynchronous. * The ' 'fetch' uses the 'promise' encapsulation, but the 'catch' function cannot catch the error directly. It needs to do something in the first 'then' function. When > 'fetch' sends POST requests, when cross-domain requests occur, 'fetch' will first send an 'OPTIONS' request to confirm whether the server is allowed to accept requests. This request is mainly used to ask whether the server is allowed to modify some operations such as headers. When the server agrees and returns 204, the actual request is sent. No two requests are made without cross-domain occurrences. __ A GET request __

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

pro.then( response =>

response.json()

).catch( err => {

console.log(err)

})

__ A POST requests __

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

const init = {

method: 'POST', header: { "Content-type": "application/x-www-form-urlencoded; }, data: 'id=12&name= ", Credentials: 'include'

}

const pro = fetch(URL, init)

pro.then( response =>

response.json()

).catch( err => {

console.log(err)

})

All requests above > can be modified using 'await' async 'not shown here. Also for the 'POST' request, where the 'data' property only supports strings, we can use ## 4. The three modules of the fetch * 'Response' module: After the 'fetch' request is sent, a server's response 'response' is obtained, which corresponds to the HTTP response. * 'Request' module: This is the module used to Request the server. The 'data', 'header' and 'method' mentioned above are all properties of the 'Request' module. * 'Headers'. This is a property on' response.headers' that manipulates the Response header information. > the detailed properties of the above three can see [miss ruan Fetch API tutorial] # # 5 (http://www.ruanyifeng.com/blog/2020/12/fetch-tutorial.html). > sends' POST 'request across domains using' FETCH ', which causes' FETCH 'to send an' OPTIONS 'request for the first time, asking if the server supports the modified header. If the server does, The real request is sent the second time. 1. The 'GET/HEAD' request of 'fetch' cannot set the 'body' property. > 2. After 'fetch' requests, no matter how many status codes are returned by the server including (4xx, 5xx), 'fetch' is not considered to be a failure. In other words, using 'catch' can not directly catch the error, which needs to be processed in the first 'then'. > encapsulates native Ajax ### 1. Implement an Ajax. > wraps native Ajax as a 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'); }}})

}

### 2. There are several Ajax states. What do they represent? > Ajax 5 states look up. * Traditional 'Ajax' uses the 'XMLHttpRequest' object to interact with the back end. 'jQuery Ajax' is the encapsulation of native 'XHR'. If there is check-in between multiple requests, the problem of callback hell will appear. * 'Axios' uses' promise' to encapsulate 'XHR', solving callback hell * 'fetch' is not 'XMLHttpRequest', 'fetch' is native js, using 'promise'. 4. What are the advantages of Fetch over Ajax? > FETCH uses Promise to facilitate asynchrony, without the problem of callback hell. ### 5. How to implement an Ajax request? What do I do if I want to send two ajax in order? The request for > to implement Ajax is the above pretend bility step for creating Ajax. 'Promise. Then ()' ### 6. How does Ajax solve the browser cache problem * Set the request header, In an ajax request with ` anyAjaxObj. SetRequestHeader (" the if-modified-since ", "0") ` or ` anyAjaxObj. SetRequestHeader (" cache-control ", "no - Cache") `. * Add a random number after the URL: '"fresh=" + Math.random()'. '"nowtTime=" + new Date().getTime()'. $.ajaxSetup({cache:false}) '$.ajaxSetup({cache:false})' So all of the AJAX on page T is going to execute this statement so you don't have to save the cache record. # 5, reference [the difference between the get and post] (https://www.oschina.net/news/77354/http-get-post-different) [Fetch API Tutorial] (http://www.ruanyifeng.com/blog/2020/12/fetch-tutorial.html) [MDN XMLHttpRequest](https://developer.mozilla.org/zh-CN/docs/Web/API/XMLHttpRequest) [MDN The fetch] (https://developer.mozilla.org/zh-CN/docs/Web/API/Fetch_API/Using_Fetch), ending # 6 > __ thank you for reading to here, If the article can be a little inspiration or help to you welcome [star] (https://github.com/lurenacm/againJS/issues), I am a linyi, see you next time. __