“This article has participated in the call for good writing activities, click to view: the back end, the big front end double track submission, 20,000 yuan prize pool waiting for you to challenge!”

The original intention of this series of articles is to “let each front-end engineer master the high frequency knowledge, for the work of power”. This is the front end of the number 28 cut, I hope friends pay attention to the public number “kite”, armed with knowledge of their minds.

As you can see from the browser console, multiple requests are made when accessing a page, and the series of requests are divided into multiple categories. What are the differences between these categories other than their types?

By looking up data and trying on your own, you can divide browser requests into three categories: generic requests, Ajax requests, and WebSocket requests, each of which has a different way of generating them.

28.1 Common Request

By normal requests, we mean that the browser will display the response body data directly, and these requests will refresh \ redirect the page. In a more understandable way, it refers to the requests displayed in the console Network panel except for the XHR and WS sections. For example, js, CSS, img resources.

28.2 the Ajax request

Ajax requests are also made by the browser, but they do nothing to the interface, just call the monitored callback function and pass in the response data. Ajax requests can be made in three ways: XHR, Fetch, Axios, and the rest are not Ajax requests.

28.2.1 XHR

The key technology that first put Ajax on the scene was the XMLHttpRequest (XHR) object, which is worth mentioning even though it’s a bit outdated now. Let’s take a look at the technology in terms of the entire life cycle of a request.

Instantiation of objects

Since you want to use XHR, the first step is to instantiate the object

const xhr = new XMLHttpRequest();
Copy the code

Initialization operation

Does an instantiation of an object need to be followed by initialization of the request to whom, through what request, and whether the request is synchronous or asynchronous

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

Request header Settings

For example, if you want to send Content in JSON format, you need to set the content-Type to Application/JSON

xhr.setRequestHeader('Content-Type', 'application/json');
Copy the code

Iv. Preparation for receiving requests

In addition to setting the common request header, the browser also needs to specify the response data type so that the response can be automatically parsed. The supported types are String, ArrayBuffer, BLOb, Document, JSON, Text, and MS-stream.

xhr.responseType('json')
Copy the code

Send a request

All the preliminary work is ready, now is the exciting moment, watch, to press the start button to send the request.

xhr.send(data)
Copy the code

Listen for response

I shout a beauty, the somebody else affirmation should respond once ah, after all appearance level is in this, don’t answer should be how not to give face of a thing!! In order to wait for a response, there are three steps:

  1. I’m going to be listening, and I’m going to be listening on onReadyStatechange right here.
  2. Wait for a positive response. ReadyStatus represents the current status, and when readyStatus is 4 (request completed), the response is considered received
  3. Process the response. I can’t process all the responses all at once. After all, I’m a face-saving person. I definitely only want to receive the information I like, and I like the status code between 200 and 299.
xhr.onreadystatechange = () => { if (xhr.readyState == 4) { if (xhr.status >= 200 && xhr.status < 300) { console.log(xhr.response); }}}Copy the code

Interrupt request

The normal process is finished, there must be abnormal process, after initiating the request I regret, do not want to get the other party’s response, at this time still after the method – interrupt the request

xhr.abort()
Copy the code

Note: This article is not a document learning, detailed use please see developer.mozilla.org/zh-CN/docs/…

28.2.2 Fetch

Internet technology is evolving so fast that a new technology (Fetch) is able to perform all the tasks of an XMLHttpRequest object, which is easier to use, has a more modern interface and can be used in modern Web tools such as Web worker threads. (Fetch must be asynchronous, XMLHttpRequest can be synchronous or asynchronous).

const payload = JSON.stringify({
    test: 'test'
});

let headersObj = new Headers({
    'Content-Type':'application/json'
});

let request = new Request('http://localhost:8080');

fetch(request, {
    method: 'POST',
    body: payload,
    headers: headersObj
})
.then((response) => response.json())
.then(console.log)
Copy the code

The code above is simple, but covers all the concepts in the Fetch API: Fetch, Headers, Request, Response, and Body mixing.

  1. The fetch ()

The fetch() method is exposed in the global scope, including the home page execution thread, module, and worker thread, and is invoked to send the browser a request to the given URL. Fetch (1) Fetch (input[, init]) : Receive two parameters, input is the resource to fetch, __init is a configuration object, the configuration needs to pass in the parameters, to meet more complex requirements. (2) Return a Promise object, thus chain processing

  1. Headers

Equivalent to the Response/Request headers, you can query these headers, or do different things for different results. This object contains retrieve, set, add, delete, and can be mounted to the configuration information in fetch after setting the required header information.

  1. Request

This object is the interface to get the resource request, exposing the request and related information. You can take an instance of this object as the first argument in the FETCH function

  1. Response

This object is the interface to get the resource response and exposes information about the response.

  1. The Body with

Provides methods related to the body in Response/Request that define its content form and how it should be handled. There are five methods provided in Body mixin to dump ReadableStream into the memory of the buffer, convert the buffer to some JavaScript object type, and produce results through promises.

(1) body.text (): Returns Promise, resolves the utF-8 format string from the buffer dump

(2) body.json (): Returns a Promise to save the buffer to json

(3) body.formData (): Returns a Promise to resolve the formData instance from the buffer dump

(4) body.arrayBuffer (): Returns a Promise to resolve the arrayBuffer that will be dumped into the buffer

(5) body.text (): Returns a Promise to resolve the Blob instance from the buffer dump

28.2.3 Axios

Axios is probably the most popular Ajax request library on the front end today, with the following features:

  1. Asynchronous Ajax request library based on Promise
  2. It can be used on both the browser and Node sides
  3. Support for request/response interceptors
  4. Support request cancellation
  5. Request/response data transformation
  6. Batch sending requests
/ / the default configuration axios. Defaults. BaseURL = 'http://localhost:8080' / / request interceptor axios. Interceptors. Request. Use (config = > { console.log('request interceptor resolved'); return config; }, error => { console.log('request interceptor rejected'); return Promise.reject(error); }); / / response interceptor axios. Interceptors. Response. Use (response = > {the console. The log (' response interceptor resolved '); return response; }, error => { console.log('response interceptor rejected'); return Promise.reject(error); }); let cancel; Axios ('/', {method: 'post', headers: {' content-type ': 'application/json'}, data: {test: 'test'}, // Cancel request cancelToken: new axios. cancelToken ((c) => {cancel = c; })}).then((response) => {console.log(response.data)}) // Cancel ();Copy the code

This code already covers most of the core content of the Axios library, including the Axios () function, default Settings, request/response interceptors, and cancel requests.

  1. axios()

Complete the corresponding configuration and send the request, call a variety of syntax sugar, students can use as needed.

  1. The default Settings

You can do a lot of global configuration with axios.defaults.xxx to improve code reuse. (Improved reuse is the perfect coding idea)

  1. Request/response interceptor

The purpose of a request interceptor is to perform a number of columns of processing before a request is sent. The purpose of the response interceptor is to perform some pre-processing on the response before the request’s callback is triggered

  1. Cancel the request

Xhr.abort () is invoked when needed by configuring the cancelToken object and caching the cancel function used to cancel the request.

See the detailed usage documentation github.com/axios/axios for more

28.3 the WebSocket request

Let’s talk about this legendary protocol, WebSocket. WebSockt communicates with servers in full duplex, two-way mode over a long connection. (Note: The same Origin policy does not apply to Websockets.)

Let ws = new WebSocket('ws://127.0.0.1:8080'); Ws.onmessage = (event) => {console.log(event. Data); ws.onMessage = (event. } // Ws.onError = () => {console.log('error'); } // When connection is closed, ws.onclose = () => {console.log('close'); }Copy the code

The above code has covered most of the concepts of WebSocket, instantiating WebSocket to establish a connection to the server; You can know the current status of WebSokcet connection through event monitoring. The send () function sends content to the server. The Message event is triggered when a server sends a message, and its payload is retrieved via the Event.data property.

1. If you think this article is good, share and like it so that more people can see it

2. Pay attention to the public number of kite, and the number of the Lord together to kill the front hundred