In frontend development, making HTTP requests to a server or an API is a common task. There are multiple ways to achieve this, two of which are XMLHttpRequest and the fetch API.
Feature | XMLHttpRequest | fetch API |
---|---|---|
Promise-based | No | Yes |
Support for streaming responses | Yes | Yes |
Simplicity | No | Yes |
Readability | No | Yes |
XMLHttpRequest is a built-in browser object that allows to make HTTP requests in JavaScript. Despite its name, it can be used to retrieve any type of data, not just XML, and it supports protocols other than HTTP.
Here's a basic example of how you might use it:
var xhr = new XMLHttpRequest();
xhr.open('GET', 'https://api.example.com/data');
xhr.onreadystatechange = function () {
if(xhr.readyState === 4 && xhr.status === 200) {
console.log(JSON.parse(xhr.responseText));
}
}
xhr.send();
In this example, a new XMLHttpRequest object is created, an HTTP GET request is opened to 'https://api.example.com/data', and a function is defined to handle the response data.
The Fetch API is a modern interface for making HTTP requests. It's promise-based, which makes it more readable and simpler to use compared to XMLHttpRequest.
Here's a basic example of how to use the fetch API:
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.log('Error:', error));
In this example, the fetch function is called with the URL of the resource you want to fetch. This returns a promise that resolves to the Response object representing the response of the request.
Both XMLHttpRequest and the fetch API are used to make HTTP requests in JavaScript. While XMLHttpRequest is older and more widely supported across all browsers, fetch provides a more powerful and flexible feature set.
Fetch's promise-based nature makes it simpler to use and more readable than XMLHttpRequest, especially when dealing with sequences of asynchronous operations. However, there may be cases where you need to use XMLHttpRequest for broader browser support. It's essential to understand both and choose the one that best fits your project's needs.