The introduction

Front-end technology is a really fast growing field, when I started three years ago there was only native XHR and Jquery Ajax, and we were stuck with the fact that Jquery 1.9 didn’t support large file requests (we ended up writing native XHR requests ourselves). JQuery Ajax has already begun to dominate the “requests” front end, axios and Fetch, respectively. This paper will try to explain the differences between them and give some of their own understanding.

1 JQuery ajax

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

I don’t need to say much about this, is the native XHR package, in addition to the addition of JSONP support. To be fair, JQuery Ajax has been updated and maintained for many years. If I had to name a few, it would be

  • Itself is for MVC programming, not in line with the current wave of front-end MVVM
  • Based on native XHR development, the architecture of XHR itself is not clear, and there is an alternative to FETCH
  • The whole JQuery project is too big, and it is unreasonable to use Ajax only to introduce the whole JQuery (personalized package solution can not enjoy CDN service).

Although JQuery had (and still has) a profound impact on our front-end development, we can see that with the rise of the VUE and REACT frameworks, the improvement of the ES specification, and more API updates, the future of JQuery as a large and complete JS library will be more and more narrow.

Conclusion: Lian Po is old and still able to eat, but there will always be a day when the food will not move.

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);
});Copy the code

After Vue2.0, You recommended using Axios instead of JQuery Ajax, which surely put Axios on a lot of people’s minds. Axios is essentially a wrapper around the native XHR, but it’s an implementation of Promise that meets the latest ES specification and has the following features on its website:

  • Create HTTP requests from Node.js
  • Supporting Promise API
  • Client support prevents CSRF
  • Provides some interfaces for concurrent requests (important, much easier to do)

This is actually a pretty cool thing to do to prevent CSRF. How do you do it? Every request you make carries a key that you get from a cookie. According to the browser’s same-origin policy, the fake site can’t get the key from your cookie. The backend can easily tell if the request is a misleading input from a user on a fake site and adopt the right strategy.

Axios provides concurrent encapsulation without fetch’s problems, and is small enough to be the most popular way to request now.

Conclusion: Who dares to cut and run, only general Axios!

3 Fetch

Fetch is touted as an alternative to AJAX, and its benefits are described in “Traditional AJAX is Dead, Fetch Lives forever” as follows:

  • Conforming to separation of concerns, without mixing inputs, outputs, and states tracked by events in one object
  • Better and more convenient ways to write, such as:
try {
  let response = await fetch(url);
  let data = response.json();
  console.log(data);
} catch(e) {
  console.log("Oops, error", e);
}Copy the code

To be honest, the above argument is not convincing to me at all, because both Jquery and Axios have helped us package XHR well enough and are convenient enough to use. Why should we bother to learn fetch?

In my opinion, the main advantages of FETCH are:

  • More low-level, rich API (request, response)
  • XHR is a new implementation in the ES specification

Everyone loves something new, and frankly, as a front end engineer, I used native XHR and found it occasionally ugly, but after using JQuery and Axios, I didn’t care about it at all. Of course, if the new FETCH can do as well, I will also choose to use fetch in order not to fall behind. This truth is actually very well understood: you have a J-8, magic changed N times, the performance reached the level of J-10, but if someone brings you a new J-10, you will not hesitate to choose the new J-10 – not only new, but also represents a new magic change potential.

However, WHEN I used fetch recently, I also encountered many problems:

  • Fetch is a low-level API that you can think of as native XHR, so it’s not as comfortable to use and needs to be wrapped

Such as:

1) Fetch only reports errors for network requests. 400,500 requests are regarded as successful requests and need to be encapsulated and processed


2) Fetch does not carry cookies by default, so configuration items need to be added


3) Fetch does not support abort and timeout control. Timeout control implemented by setTimeout and Promise.reject cannot prevent the request process from continuing to run in the background, resulting in waste of traffic


4) Fetch has no way of natively monitoring the progress of requests, whereas XHR does

PS: The specific problems of FETCH can be referred to: Fetch is Not as beautiful as you think, common Problems and Solutions used by Fetch

I’m going to go back to using Jquery or Axios — that’s what I’m going to do. However, it must be mentioned that I have found fetch to have a front end application that XHR can’t match: cross-domain processing.

We all know that because of the same-origin policy, browser requests can cross domains at will — you must have a cross-domain header or use JSONP. However, the fetch can set mode to “no-cors”, as shown below:

fetch('/users.json', {
    method: 'post', 
    mode: 'no-cors',
    data: {}
}).then(function() { /* handle response */ });Copy the code

After that we get a return of type “opaque”. Need to point out that this request is really after arrived in Taiwan, so we can use this method to report information, before we image. The SRC method in a more choice, in addition, we can see the request in the network background Settings cross-domain head after the actual return, will help us to debug interface (of course, We can also do this via chrome. In short, FETCH is still not very easy to use. I have tried several fetch packages, but none of them are satisfactory.

Conclusion: Chief’s child, still need to grow up

conclusion

If you dragged it straight to the bottom of the article, just know that there is no brain to use Axios now, Jquery is old and clumsy, fetch is young and young, only Axios is old!