ajax, axios and fetch

1.jQuery ajax

$.ajax({
   type: 'POST',
   url: url,
   data: data,
   dataType: dataType,
   success: function () {},
   error: function () {}
});

Traditional Ajax refers to XMLHttpRequest (XHR), the earliest technology for sending back-end requests. It belongs to the original js, and the core uses the XMLHttpRequest object. If there is a sequential relationship between multiple requests, there will be callback hell.
JQuery ajax is a encapsulation of native XHR, in addition to adding support for JSONP. After years of update and maintenance, it is really very convenient, and the advantages need not be said; if you have to cite a few shortcomings, you may only:
1. It is programming for MVC, which does not meet the current wave of front-end MVVM
2. Based on the original XHR development, the structure of XHR itself is not clear.
3. The whole project of JQuery is too big, and it is very unreasonable to use Ajax to introduce the whole JQuery (it takes a personalized package and cannot enjoy CDN service)
4. It does not meet the principle of separation of concerns (Separation of Concerns)
5. Configuration and The calling method is very confusing, and the event-based asynchronous model is not friendly.
PS: MVVM (Model-View-ViewModel), derived from the classic Model-View-Controller (MVC) pattern. The emergence of MVVM promotes the separation of GUI front-end development and back-end business logic, greatly improving the efficiency of front-end development. The core of MVVM is the ViewModel layer, which is like a value converter, which is responsible for converting the data objects in the Model to make the data easier to manage and use. This layer performs two-way data binding with the view layer. Data interaction between the lower and the Model layer through the interface request, plays the role of up and down. The View layer displays not the data of the Model layer, but the data of the ViewModel. The ViewModel is responsible for interacting with the Model layer. This completely decouples the View layer and the Model layer. This decoupling is essential. It is the separation of front and back ends. The most important part of the implementation of the plan.
As shown in the figure below:
image.png

2.axios

axios({
    method: 'post',
    url: '/user/12345',
    data: {
        firstName: 'Fred',
        lastName: 'Flintstone'
    }
})
.then(function (response) {
    console.log(response);
})
.catch(function (error) {
    console.log(error);
});

After Vue2.0, You Yuxi recommends that everyone use axios to replace JQuery ajax, presumably axios has entered the eyes of many people.
axios is a Promise-based HTTP client for browsers and nodejs. It is essentially a encapsulation of native XHR, except that it is an implementation version of Promise and conforms to the latest ES specifications. It has the following characteristics:
1. View from Create XMLHttpRequest in the server
2. Support Promise API
3. Client support to prevent CSRF
4. Provide some concurrent request interfaces (important, convenient for many operations)
5. Create http request from node.js
6. Intercept request and response
7 . Convert request and response data
8. Cancel request
9. Automatically convert JSON data
PS: Prevent CSRF: Let each request of you carry a key obtained from the cookie. According to the browser’s same-origin policy, the fake website is You can’t get the key in the cookie, so the backend can easily identify whether the request is a misleading input by the user on the fake website, so as to adopt the correct strategy.

3.fetch

try {
  let response = await fetch(url);
  let data = response.json();
  console.log(data);
} catch(e) {
  console.log("Oops, error", e);
}

Fetch claims to be an alternative to AJAX, which appeared in ES6 and uses the promise object in ES6. Fetch is designed based on promise. The code structure of Fetch is much simpler than ajax, and the parameters are a bit like jQuery ajax. However, it must be remembered that fetch is not a further encapsulation of ajax, but native js, without using the XMLHttpRequest object.
Advantages of fetch:
1. In line with the separation of concerns, there is no mixing of input, output and the state tracked by events in one object.
2. A better and more convenient way of writing.
Frankly speaking, the above reasons are not very convincing to me. , Because both Jquery and Axios have helped us to encapsulate xhr well enough, and it is convenient enough to use, why should we spend so much effort to learn fetch?
I think the main advantages of fetch are:

  1. The syntax is concise and more semantic
  2. Based on standard Promise implementation, support async/await
  3. Convenient isomorphism , use isomorphic-fetch
    4. More low-level, rich API (request, response)
    5. Break away from XHR, it is a new implementation in the ES specification.
    Recently, I encountered many problems when using fetch :
    Fetch is a low-level API, you can think of it as a native XHR, so it is not so comfortable to use and needs to be encapsulated.
    E.g:

1) Fetch only reports errors for network requests. Both 400 and 500 are regarded as successful requests. When the server returns 400, 500 error codes, it will not reject. Only when network errors cause the request to be unable to complete, fetch will be rejected.
2) Fetch does not carry cookies by default, you need to add a configuration item: fetch(url, {credentials:'include'})
3) Fetch does not support abort, does not support timeout control, use setTimeout and Promise.reject to achieve timeout control and The request process cannot be prevented from continuing to run in the background, causing a waste of traffic.
4) Fetch has no way to
natively monitor the progress of the request, but XHR can summarize: Axios not only provides concurrent encapsulation, but also does not have the various problems of fetch, and the volume is relatively small. Small, well-deserved request method should be used most now.

Guess you like

Origin blog.csdn.net/w19981225/article/details/108278904