In recent days, due to a series of reasons such as writing scripts, I suddenly found that many mainstream websites have started to use Fetch for network requests in large numbers, and I felt that Fetch would be Out if I didn’t learn more. Therefore, I spent some time to study the relevant knowledge of Fetch, and found that Fetch was not discussed much. Many of them are a year or even two years old, and most of them almost always end up with Axios being better than Fetch.
In fact, Axios is better than Fetch in terms of my personal experience. So why do many websites of large companies start to use Fetch for network requests? With this question in mind, I searched a lot of materials and tried using Axios and Fetch for the same requests by myself. One final conclusion: Fetch’s advantage is only in browser native support.
That’s right, Fetch actually has almost no advantage over Axios (other than browser native support), Axios is better than Fetch in every way, and Fetch has to manually encapsulate some of Axios’s functionality.
I’ve captured a few requests from larger sites:
The nuggets:
YouTube:
Zhihu:
Note that Axios is a wrapper around XMLHttpRequest, while Fetch is a new interface way to Fetch resources, not a wrapper around XMLHttpRequest.
The main difference is that Fetch is browser-native, while Axios requires the introduction of the Axios library.
1. Heat level
While there is no direct comparison, we can see from the NPM package downloads:
Since Fetch is not supported in Node environment by default, the package Node-Fetch must be used. However, the weekly downloads of this package have been climbing, and it can be seen that it has reached over 20 million downloads per week. This is just Node, and browsers don’t need third-party packages by default.
Here’s the Axios download numbers, and you can see how they’re going up, and the various ways Axios wraps are really good.
This article will focus on the following aspects of comparison:
- compatibility
- The basic grammar
- Response timeout
- Transformation of data
- HTTP interceptor
- At the same time request
2. Compatibility problems
Axios is compatible with Internet Explorer, and Fetch is not supported in Internet Explorer and some older browsers, but there is a library that supports Fetch in older browsers called WHATWG-FETCH, which allows you to use Fetch in older browsers, And many web sites are no longer compatible with Internet Explorer in order to reduce costs.
Note: You may also need to use the Promise compatibility library on older browsers.
Compatibility of Fetch by browser:
3. Request mode
Let’s take a look at how to use Axios and Fetch for requests.
Axios:
const options = {
url: "http://example.com/".method: "POST".headers: {
Accept: "application/json"."Content-Type": "application/json; charset=UTF-8",},data: {
a: 10.b: 20,}}; axios(options).then((response) = > {
console.log(response.status);
});
Copy the code
Fetch:
const url = "http://example.com/";
const options = {
method: "POST".headers: {
Accept: "application/json"."Content-Type": "application/json; charset=UTF-8",},body: JSON.stringify({
a: 10.b: 20,})}; fetch(url, options).then((response) = > {
console.log(response.status);
});
Copy the code
The biggest difference lies in the way data is passed. Axios is placed in the data attribute and passed as an object, while Fetch needs to be placed in the body attribute and passed as a string.
4. The response times out
The corresponding timeout setting for Axios is very simple, just setting the timeout property directly, while Fetch is much more difficult to set up than Axios, which is one of the reasons why many people prefer Axios to Fetch.
axios({
method: "post".url: "http://example.com/".timeout: 4000.// The request will time out if there is no response within 4 seconds
data: {
firstName: "David".lastName: "Pollock",
},
})
.then((response) = > {
/* Process the response */
})
.catch((error) = > console.error("Request timed out"));
Copy the code
Fetch provides the AbortController property, but it’s not as easy to use as Axios.
const controller = new AbortController();
const options = {
method: "POST".signal: controller.signal,
body: JSON.stringify({
firstName: "David".lastName: "Pollock",})};const promise = fetch("http://example.com/", options);
// If there is no response within 4 seconds, time out
const timeoutId = setTimeout(() = > controller.abort(), 4000);
promise
.then((response) = > {
/* Process the response */
})
.catch((error) = > console.error("Request timed out"));
Copy the code
5. Transformation of data
Another nice thing about Axios is that it automatically transforms the data, unlike Fetch, which requires the user to manually convert the data.
// axios
axios.get("http://example.com/").then(
(response) = > {
console.log(response.data);
},
(error) = > {
console.log(error); });// fetch
fetch("http://example.com/")
.then((response) = > response.json()) // The response data needs to be converted
.then((data) = > {
console.log(data);
})
.catch((error) = > console.error(error));
Copy the code
Fetch provides the following conversion apis:
- arrayBuffer()
- blob()
- json()
- text()
- formData()
When using Fetch, you need to know what the data type is after the request and then use the corresponding method to convert it.
Fetch can implement Axios’ automatic transformation function through some encapsulation. As for how to implement it, I will not talk here because I have not studied it, but it should be easy to implement, but it will take some time to write a robust implementation process.
HTTP interceptor
One of Axios’s big selling points is that it provides an interceptor that can handle requests or responses in a unified way. If you have seen a complete project request wrapper, you must know Axios’s interceptor, which is a very important feature.
It can be used to attach tokens to requests, add time stamps to requests to prevent request caching, and intercept responses. Once the status code does not meet expectations, the response message will be directly displayed on the interface in the form of pop-ups, such as password error, server internal error, form verification failure and other problems.
axios.interceptors.request.use((config) = > {
// Request parameters are processed before a request is made
return config;
});
// Send a GET request
axios.get("http://example.com/").then((response) = > {
console.log(response.data);
});
Copy the code
Fetch has no interceptor functionality, but it’s not that hard to do, simply overriding the global Fetch method.
fetch = ((originalFetch) = > {
return (.arguments) = > {
const result = originalFetch.apply(this.arguments);
return result.then(console.log("Request sent"));
};
})(fetch);
fetch("http://example.com/")
.then((response) = > response.json())
.then((data) = > {
console.log(data);
});
Copy the code
7. Simultaneous requests
Concurrent requests are not used much in projects, but they may be used occasionally.
Axios:
axios
.all([
axios.get("https://api.github.com/users/iliakan"),
axios.get("https://api.github.com/users/taylorotwell"),
])
.then(
axios.spread((obj1, obj2) = >{... }));Copy the code
Fetch:
Promise.all([
fetch("https://api.github.com/users/iliakan"),
fetch("https://api.github.com/users/taylorotwell"),
])
.then(async ([res1, res2]) => {
const a = await res1.json();
const b = await res2.json();
})
.catch((error) = > {
console.log(error);
});
Copy the code
Browser native support
The only thing Fetch has beaten Axios is native support for modern browsers.
In a responsible manner (actually because this article was difficult to write… In recent days, I have tried to use Fetch for many times. After I got used to it, I found it quite useful. The most important thing is that the browser supports Fetch native, unlike Axios, which needs to introduce a package and test some interfaces to directly use Fetch in Chrome for requests. Especially when you’re writing crawlers or scripts, you can use Fetch directly from the Chrome console on the current web page with little configuration.
In the picture above, open the Chrome console in Zhihu and call the Personal data API of Zhihu. You can see that the data can be obtained successfully.
9. The last
Fetch can do everything Axios can do, but it needs to be wrapped in its own right, and if you don’t like the hassle of using Axios directly in your project, it’s a smart choice, depending on whether you want to use the browser’s built-in API.
Sometimes it’s inevitable that newer technologies will replace older ones, so Fetch will one day replace XMLHttpRequest, and maybe later the Axios library will use Fetch requests instead.
Reference article: Axios or Fetch (): Which should you use?