✅What is the difference between fetch and XMLHTTPRequest?
Anthony Max
Posted on November 13, 2024
Hello everyone! While working on an interesting project, I had an idea to tell about the difference between fetch
and XMLHTTPRequest
. In fact, the question sounds quite interesting if you know the history of its creation, in the sense that it is a little incorrect, but you still need to know about it, because, let's say, for me as a developer, when I deal with all sorts of APIs every day, it is useful to know so as not to create unnecessary code.
What is XMLHTTPRequest and a brief history of its creation
In javascript, XMLHttpRequest
objects are used to interact with servers. You can retrieve data from a URL without having to do a full page refresh. This enables a Web page to update just part of a page without disrupting what the user is doing. But generally speaking, to put it bluntly, it is an API. And when we hear this, we immediately remember the concepts of event loop, asynchronous (when the code execution will be completed after a certain time), etc. For example, code using XMLHTTPRequest
looks like this:
const xhr = new XMLHttpRequest();
// method, URL, [isAsync, user, password]
xhr.open("GET", "/api/getPage");
// body
xhr.send()
The history of the creation of XMLHTTPRequest
itself takes us back to the distant years when dinosaurs walked... Okay, just kidding. In fact, this API was first developed by Microsoft and was introduced in the Outlook on the web component of the Microsoft Exchange Server software 2000 product.
Back then, it was called differently - IXMLHTTPRequest
and was a little, if one can say so in the first versions of the interface, different from what it is now. That is, the base obviously remained, but it is obvious that adjustments were made over 25 years. Later, it was added to MSXML 2.0, and even later, to Internet Explorer 5 in March 1999.
Then, Mozilla programmers developed their own version of API based on IXMLHTTPRequest
, then called nsIXMLHttpRequest
, and made it accessible through our beloved XMLHttpRequest
. All this was added to Gecko version 0.6 in December 2000 (Gecko is a browser engine used in FireFox and many other places). At that time, there was no such thing as FireFox, because its first version was released in September 2002 and was called Phoenix, then FireBird and only by 2004 FireFox. Then, before all this, there was Netscape Navigator, but the confrontation with Internet Explorer and that's it - that's another story, which there is no point in writing in this article. Later, support was added to Safari, Opera and other browsers. So when people tell you that this object is used for compatibility with old browsers, then of course they are right, because it takes us to the late 90s, when web development was just developing. You can even remember the time of the dotcom bubble, but, admittedly, it was a little earlier, or at that time (if we take Internet Explorer), but anyway it was then.
So what's the difference?
So, returning to the question about the difference, the most important difference is already hidden in history, because XMLHTTPRequest
is just an old, but supported API, and fetch
is just a new API, which kind of replaces it. As of today, XMLHTTPRequest 2.0
was released in January 2012, but the latest edition of 1.0 standard was released in December of the same year. This is the current standard for this object. But now imagine the faces of the developers who wrote this all the time:
var xhr = new XMLHttpRequest();
xhr.open('GET', '/api/getData', true);
xhr.onload = function () {
if (xhr.status >= 200 && xhr.status < 300) {
var data = JSON.parse(xhr.responseText);
console.log(data);
} else {
console.error('Request failed with status:', xhr.status);
}
};
xhr.onerror = function () {
console.error('There was a network error.');
};
xhr.send();
instead of this
fetch('/api/getData')
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then(data => {
console.log(data);
})
.catch(error => {
console.error('There was a problem with the fetch operation:', error);
});
a few years ago. That's the only thing that comes to mind right away.
But seriously, here is a short list of differences:
Promise-oriented: The Fetch API uses promises, which makes it easier to work with asynchronous code and allows you to use convenient constructs like
.then()
andasync
andawait
.Simplified interface: The Fetch API has a simpler and more intuitive syntax. For example, to make requests, you don’t need to create an object and set its properties, as is the case with XHR.
Support for new features: The Fetch API supports new features such as Request and Response objects, which provide convenient methods for working with requests, responses, and their transformations.
Support for streams: The Fetch API supports streaming data, which allows you to work with large amounts of data as it is received.
Canceling requests: Although the Fetch API does not have built-in support for canceling requests, you can use the abort controller to do so, which makes managing requests more flexible.
Improved customization: The Fetch API provides more options for configuring requests, such as setting headers, caching modes, and other parameters.
cors
support: The Fetch API provides more flexibility in working with CORS (Cross-Origin Resource Sharing), which allows for more flexible configuration of requests to resources from other domains.Better error handling: When working with the Fetch API, you can better handle response statuses, since a request error (e.g. network unavailable) will reject the promise, while a successful response with a 4xx or 5xx code will not reject it, and you will need to check the status code yourself.
This is of course not me, but it's just a cool picture
And, of course, there are many more differences, but I don’t see the point in listing them now, because by all parameters it is clear that this is simply an improved version of the old standard for modern browser requirements.
Afterword
At first I thought to write one line that fetch
is a newer standard, but it would be too simple and uninformative, when in fact there is a lot of cool stuff there that could be told. You can write a whole article about fetch alone, but there is no particular point in this article. But, overall, in my opinion, everything seems ok.
Thank you very much for reading the article!
P. S.
If you liked this article, it would be great if you rated HMPL on GitHub with a star. Thanks!
Posted on November 13, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.