The main difference between Fetch and XMLHttpRequest is that the Fetch API uses Promises, hence avoiding callback hell. If you are new to promises then check out JavaScript Promises: an Introduction . You can make use of polyfill for browsers that are not currently supported.
Fetch is compatible with all recent browsers including Edge, but not with Internet Explorer. Therefore, if you are looking for maximum compatibility, you will continue to use Ajax to update a web page. If you also want to interact with the server, the WebSocket object is also more appropriate than fetch.
The Fetch API is a modern alternative to XMLHttpRequest . The generic Headers, Request, and Response interfaces provide consistency while Promises permit easier chaining and async/await without callbacks.
Without question, some developers prefer Axios over built-in APIs for its ease of use. But many overestimate the need for such a library. The fetch() API is perfectly capable of reproducing the key features of Axios, and it has the added advantage of being readily available in all modern browsers.
There are a few things that you can do with fetch and not with XHR:
no-cors
requests, getting a response from a server that doesn't implement CORS. You can't access the response body directly from JavaScript, but you can use it with other APIs (e.g. the Cache API);There are a couple of things that you can do with XHR that you can't do yet with fetch, but they're going to be available sooner or later (read the "Future improvements" paragraph here: https://hacks.mozilla.org/2015/03/this-api-is-so-fetching/):
This article https://jakearchibald.com/2015/thats-so-fetch/ contains a more detailed description.
ReadableStream
instances as request bodies is yet to come)mozAnon
flag or the AnonXMLHttpRequest
constructor)FormData
instancesfetch
's no-cors
modeThe answers above are good and provide good insights, but I share the same opinion as shared in this google developers blog entry in that the main difference (from a practical perspective) is the convenience of the built-in promise returned from fetch
Instead of having to write code like this
function reqListener() {
var data = JSON.parse(this.responseText);
}
function reqError(err) { ... }
var oReq = new XMLHttpRequest();
oReq.onload = reqListener;
oReq.onerror = reqError;
oReq.open('get', './api/some.json', true);
oReq.send();
we can clean things up and write something a little more concise and readable with promises and modern syntax
fetch('./api/some.json')
.then((response) => {
response.json().then((data) => {
...
});
})
.catch((err) => { ... });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With