This is the 24th day of my participation in the August Text Challenge.More challenges in August

1. Characteristics and problems of traditional request interaction

1-1. Characteristics of traditional request interaction

Client request -> server (Node Web Server) process request -> process data (data + template rendering) -> return rendered data to the front end.

Question:

  • Processing data (data + template rendering) : The server needs to render the data and template each time, occupying the server’s resources.

  • If only a small part of the data is being retrieved, why does this piece of data need to be returned with an entire rendered page

  • Each time new content is requested, a new request is sent through the browser (if sent through the browser, the browser will reload the entire page if the data is returned).

  • Server Performance

  • The user experience

2. No refresh is performed asynchronously

Through a JAVASCRIPT API provided by the browser, it can send a request to the server. The data returned by the request will be received by JS, and then we can control the rendering of this data (DOM manipulation) through JS.

Modern browsers support multiple apis with HTTP

XMLHttpRequest

Advantages: Early, browsers support the best apis.

Disadvantages: The API is relatively old and some modern JS language features need to be wrapped (e.g. Promise).

Fetch

Strengths: Relatively new, naturally good support for some features (Promise, CORS).

Disadvantages: Compatibility, lack of event support.

3. Asynchronous request process and implementation – XMLHttpRequest

The XMLHttpRequest (XHR) object is used to interact with the server. With XMLHttpRequest, you can request a specific URL to retrieve data without refreshing the page. This allows the web page to update parts of the page without affecting the user’s actions. XMLHttpRequest is widely used in AJAX programming.

Reference: developer.mozilla.org/zh-CN/docs/…

The basic process of using XHR to communicate with the server is as follows:

3-1. Create an XMLHttpRequest object

let xhr = new XMLHttpRequest();
Copy the code

3-2. Set the request parameters

xhr.open(string method, string url, boolean async);
Copy the code

Method:

HTTP request methods, including GET, POST, PUT, PATCH, and DELETE…… .

Url:

The URL of the resource requested.

Async:

Whether to send requests in asynchronous mode. The default value is true, and true is recommended for the main process.

False indicates that the synchronous mode is used, which affects user experience.

Reference: developer.mozilla.org/zh-CN/docs/…

3-3. Send the request

The request is officially issued only when the send method is called:

xhr.send();
Copy the code

3-4. Events related to listening requests

Since we are sending requests asynchronously, we need to get relevant feedback through event callbacks.

As we know, an interaction consists of two phases: request (data upload) and response (data download).

Response to related events:

Loadstart:

Triggered when response data is received. You can also use the onloadStart attribute.

Progress:

Periodically triggered when the request receives more data. You can also use the onProgress property.

Loadend:

Fired when the request ends, whether the request succeeds (LOAD) or fails (abort or error). You can also use the onLoadEnd attribute.

Load:

Triggered when the XMLHttpRequest request completes successfully. You can also use the onload attribute.

Timeout:

Triggered when no response has been received within the preset time. You can also use the onTimeout property.

Abort:

Triggered when request is stopped, such as when the program calls xmlHttprequest.abort (). You can also use the onabort attribute.

Error:

Triggered when the request encounters an error. You can also use the onError attribute.

xhr.onload = function() {
  console.log('Request completed');
}
Copy the code

3-5. Get data

The XHR object also provides a number of properties and methods to help us obtain some key information:

ReadyState:

For the status code of the request, see developer.mozilla.org/zh-CN/docs/…

A readyStatechange event is also provided to listen for readyState changes.

The response:

The original content returned depends on the responseType.

ResponseType:

The type of response data returned, configurable. Reference: developer.mozilla.org/zh-CN/docs/… .

The responseText:

Returns response data converted to text type. ResponseType =’ responseType ‘;

Status:

Response status code.

StatusText:

Response status text.

Timeout:

The request timeout period is set.

Upload:

Upload related.

WithCredentials:

Cross-domain authorization related.

The getAllResponseHeaders () :

Get all response header information.

GetResponseHeader (string name) :

Gets the specified header information.

OverrideMimeType (string mimeType) :

Overwrite response header information.

SetRequestHeader (string header, string value) :

XMLHttpRequest. SetRequestHeader () is to set the HTTP request header. This method must be called between the open() method and send() method.

Abort () :

Cancel the request.

. xhr.onload =function() {
  console.log(this.responseText); }...Copy the code

4. Request configuration parameters and data Settings

4-1. Dynamic routing

.let itemId = 1;
xhr.open('get'.`/item/${itemId}`); .Copy the code

4-2, the queryString

.let page = 1;
let limit = 5;
xhr.open('get'.`/items? page=${page}&limit=${limit}`); .Copy the code

4-3, the body

urlencoded

.let username = 'zMouse';
let password = '123456';
xhr.open('post'.'/login');

// Set the header information
xhr.setRequestHeader('Content-Type'.'application/x-www-form-urlencoded');
// The text is passed in via send
xhr.send(`username=${username}&password=${password}`);
Copy the code

json

.let username = 'zMouse';
let password = '123456';
xhr.open('post'.'/login');

// Set the header information
xhr.setRequestHeader('Content-Type'.'application/json');
// The text is passed in via send
xhr.send( JSON.stringify( {username, password} ) );
Copy the code

form-data

.let username = 'zMouse';
let password = '123456';
xhr.open('post'.'/login');

// Use FormData to build data
let fd = new FormData();
fd.append('username', username);
fd.append('password', password);
// If FormData is used as a parameter, XHR automatically sets the corresponding header and data format when sending the request
xhr.send( fd );
Copy the code

5. Upload and download

XHR provides an Upload attribute, which is an XMLHttpRequestUpload object that represents the progress of the upload.

The event The information type of the corresponding attribute
onloadstart To get started
onprogress Data transfer in progress
onabort Fetch operation terminated
onerror For failure
onload To be successful
ontimeout The fetch operation did not complete within the time specified by the user
onloadend Obtaining completion (successful or not)
.// <input type="file" id="avatar" />
let avatar = document.querySelector('#avatar');

avatar.onchange = function() {
  
  let xhr = new XMLHttpRequest();
  
  xhr.open('post'.'/avatar');
  
  xhr.upload.onloadstart = function() {
    console.log('Start uploading');
  }
  xhr.upload.onprogress = function(e) {
    console.log( 'Upload progress:${e.loaded}/${e.total} ` );
  }
  xhr.upload.onload = function() {
    console.log('Upload successful');
  }
  
  let fd = new FormData();
  // Get the selected file in input
  fd.append('avatar', avatar.files[0]); xhr.send(fd); }...Copy the code