Author: Jerry
The introduction
The front end is a rapidly developing field, and in the front end stack, the front end request is the most visible field, through the request interface data, can make a static page dynamic. This paper analyzes the technical evolution of front-end request and its advantages and disadvantages one by one from the timeline of front-end development. In view of this topic, the author has consulted relevant information to give his own understanding. If there are any mistakes, please kindly point out.
XMLHttpRequest
XMLHttpRequest was one of the earliest ways to exchange data with a server. With XMLHttpRequest, developers can finally update a web page without reloading the page, and request to accept and send data after the page loads. All browsers can get the XMLHttpRequest object:
var xhr = new XMLHttpRequest(); // Get the XHR objectCopy the code
However, XMLHttpRequest is a crude, low-level object, and the way it is created varies from browser to browser. Here are the compatible methods:
var xhr; if (window.XMLHttpRequest) { // Mozilla, Safari... xhr = new XMLHttpRequest(); } else if (window.ActiveXObject) { // IE try { xhr = new ActiveXObject('Msxml2.XMLHTTP'); } catch (e) { try { xhr = new ActiveXObject('Microsoft.XMLHTTP'); //IE5,6} catch (e) {}}}Copy the code
Initiate a GET request using XMLHttpRequest
/ / get request XHR. Open (" get ", "test1. TXT", true); xhr.send();Copy the code
The complete POST request code is as follows:
var xhr; if (window.XMLHttpRequest) { // Mozilla, Safari... xhr = new XMLHttpRequest(); } else if (window.ActiveXObject) { // IE try { xhr = new ActiveXObject('Msxml2.XMLHTTP'); } catch (e) { try { xhr = new ActiveXObject('Microsoft.XMLHTTP'); } catch (e) {} } } if (xhr) { xhr.onreadystatechange = onReadyStateChange; xhr.open('POST', '/api', true); // Set content-type to application/x-www-form-urlencoded // Transfer data in form xhr.setRequestHeader(' content-type ', 'application/x-www-form-urlencoded'); xhr.send('username=admin&password=root'); Function onReadyStatechange () {if (xhr.readyState === 4 &&xhr.status === = 200) { Console. log(' executed successfully '); } else {console.log(' error executing '); }}Copy the code
Jquery Ajax
Speaking of Jquery, this was the era that dominated the front end for more than 10 years, completely solving the UI layer and data layer interaction problem, until the advent of the three frameworks (Angular/React/Vue) and the front end entered the MVVM wave. Ajax encapsulates XHR, making it easier for developers to use.
$. Ajax ({// 表 示 type: 'POST', url: url, data: data, dataType: dataType, success: function () {}, error: function () {} }); $.get(url,function(){}); / / get request $. Post (url, body, function () {}); / / post request $. GetJSON (url, function () {}); // GET requests load Json encoding from the serverCopy the code
Advantages:
- Encapsulation of native XHR
- Programming for MVC
- Perfect compatibility
- Support the json
Disadvantages:
- Do not conform to the MVVM
- The asynchronous model is not modern enough, does not support chaining, and the code is not readable
- Jquery as a whole is too big and expensive to introduce
Fetch
Fetch is actually a new world, out-of-xHR, full Promise based asynchronous processing mechanism that is much simpler to use than Ajax.
The code using FETCH is much more organized than XHR
fetch(url).then(function(response) {
return response.json();
}).then(function(data) {
console.log(data);
}).catch(function(e) {
console.log("Oops, error");
});Copy the code
After using the arrow function of ES6
fetch(url).then(response => response.json())
.then(data => console.log(data))
.catch(e => console.log("Oops, error", e))Copy the code
Advantages:
- More low-level, rich API (request, response)
- Simple syntax, free from XHR, based on ES new Promise design
You might think fetch is really nice, but be aware that fetch itself is a low-level API, and it’s not meant to encapsulate various functions or implementations like the $. Ajax or Axios libraries you’re used to.
Therefore, it has certain disadvantages:
- Compatibility is poor, low level browsers are not supported, need to implement fetch polyfill. The idea is simple: check whether the browser supports the native FETCH. If not, XMLHttpRequest is still used and Promise is encapsulated. Common polyfills include es6-Promise, Babel-polyfill,fetch- IE8, etc
- If JSONP is not supported, fetch-jsonp can be introduced
FetchJsonp (url, {timeout: 3000, jsonpCallback: 'callback' }).then(function(response) { console.log(response.json()); }).catch(function(e) { console.log(e) });Copy the code
- Without interceptors, you need to wrap an extra layer or fetch-interceptor
- The cookie is not configured by default
Fetch (URL,{credentials: 'include' //include indicates that cookies can be both same-domain and cross-domain, 'same-origin' indicates that same-domain only});Copy the code
- Abort is not used and timeout timeout handling is not supported
This can be implemented using promise.race (). The promise.race (iterable) method returns a Promise object, as long as any of the iterable promises are resolved or rejected. The external Promise is resolved or reject with the same value.
- Unable to get progress status
The getReader() method is implemented in response.body of the fetch to read the raw byte stream, which can be read in a loop. Refer to javascript – Progress indicators for fetch? – Stack Overflow2016 – the year of web streams
Axios
Axios is also a relatively new library for network requests, and has become a standard VUE network request, which is also very popular. It is itself an encapsulation of native XHR.
- Support node to create HTTP requests
- Supporting Promise API
- The client prevents CSRF: each request carries a cookie received key
- Intercept requests and responses
- Cancelable request
While AXIos is essentially a wrapper around native XHR, it also relies on the implementation of native ES6 Promise, which, like FETCH, requires Polyfill compatibility.
The installation
//npm
npm install axios
//cdn
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>Copy the code
The basic usage is as follows:
axios({ method: 'GET', url: url, }).then(res => {console.log(res)}).catch(err => {console.log(err)}) // get request axios.get(url).then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); }); Post (' /user ', {name: 'Jerry', lastName: 'Liang'}). Then (function (response) {console.log(response); }) .catch(function (error) { console.log(error); });Copy the code
Handling of special scenarios
Often appear in the process of development, which may be embarrassing scene is to request more of serial and parallel, concurrency is relatively easy to solve, there is no callback hell, but the code readability slag will become very easily, and the serial problems is desperate for a front end, is the best way to the backend to merge, if you don’t do the processing of the backend, the front must be to face the callback hell.
Multirequest serial
// ajax $.ajax({ url: '', data: '', success: function (data) { $.ajax({ url: '', data: '', success: Function (data) {$. Ajax ({// such a layer of a layer})}}) //axios axios.get(url). Then (res => {return axios.get(url,{ {name:result.name} }); }). Then (res => {// such a nested layer});Copy the code
Multirequest parallelism
Var num = 0; var num = 0; var num = 0; function all(){ num++; If (n>=3)console.log(' three requests completed '); } $. Ajax ({url: ", data: ", success: function (data) {console.log("ajax request 1 completed "); all(); }}) $. Ajax ({url: ", data: ", success: function (data) {console.log("ajax request 2 completed "); all(); }}) $. Ajax ({url: ", data: ", success: function (data) {console.log("ajax request 3 completed "); all(); } }) //axios function getInfo() { return axios.get(url); } function getUser() { return axios.get(url); } axios.all([getInfo(), getUser()]).then(axios.spread(function (info, user) {// Both requests are now executed}));Copy the code
How to choose (personal understanding, for reference only)
- The first thing to be sure is that if your code is still based on Jquery, ajax is definitely your best bet.
- If you are using any MVVM framework, it is recommended to use Axios mindless, fetch in real project use requires all kinds of wrapping and exception handling, not out of the box, and Axios can replace $.ajax directly.
- If fetch is to be used, you can certainly encapsulate your own set of best practices.