JavaScript Fetch API vs XMLHttpRequest Explained
Learn how to request data from an API in JavaScript using the modern Fetch API and the classic XMLHttpRequest object, then handle the response.

Contents

Fetch and XMLHttpRequest with JavaScript
To fetch data from an API with JavaScript, you first need to create an XMLHttpRequest (XHR) object. This object lets a web page send an HTTP request and receive the response.
For example, the following code block shows a data fetch operation that sends a GET request and returns a string from an API:
// Create an XHR object
var xhr = new XMLHttpRequest();
// Specify the request type and URL
xhr.open('GET', 'https://api.example.com/endpoint');
// Send the request and handle the response
xhr.onload = function() {
if (xhr.status === 200) {
// Response successful: handle the data
var data = JSON.parse(xhr.responseText);
console.log(data);
}
else {
// Response failed: show an error message
console.log('API hatası: ' + xhr.status);
}
};
xhr.send();
In this example, the XMLHttpRequest.open() method specifies a GET request and the API endpoint. Then, the XMLHttpRequest.onload event handler handles the response. This event handler processes the data if the response is successful and shows an error message if it fails. Finally, the request is sent with the XMLHttpRequest.send() method.
One thing to note is that in this example, the data is returned in JSON format. Therefore, the data is processed as an array or object with the JSON.parse() method.
As in this example, you can use the XHR object to fetch data from an API with JavaScript. However, this approach is old and is no longer recommended. As a newer and easier-to-use alternative, you can use the fetch() API. The following code block performs the same operation using the fetch() API:
fetch('https://api.example.com/endpoint')
.then(response => response.json())
.then(data => {
console.log(data);
})
.catch(error => {
console.log('API hatası: ' + error);
});
In this example, the fetch() function sends a GET request and returns a Promise object for the response. The response is handled with the Promise object’s then() method. If the response is successful, the data is processed as JSON with the response.json() method, and the data is handled in the second call to the then() method. If the response fails or an error occurs, an error message is shown with the catch() method.
As shown in this example, using the fetch() API to fetch data from an API with JavaScript offers an easy and modern method. However, you might also consider using the XMLHttpRequest object for more customization. But in addition to what’s described above, we need to understand the fetch topic a little more.
fetch() takes a URL and optionally a request object and returns a Promise object. The request object is used to specify the request details (for example, sending data, headers, and so on). For example, the following code block will show a data fetch operation that sends a GET request and returns a string from an API. I think the last example we gave above actually explains this quite well.
Actually, the fetch() function above sends a GET request and converts the returned response into a Promise object. It handles the response with the Promise object’s then() method, and if the response is received successfully, that is, if the returned status is 200 OK, the data is processed as a string with the response.text() method, and the data is handled in the second call to the then() method. If the response fails or an error occurs, we can show an error message with the catch() method. (Since it just came to mind, let’s also examine this in an article too 🙂
One thing to note is that the fetch() API returns a Promise object. Therefore, you work on the Promise with the then() and catch() methods. These methods are called when the Promise resolves or an error occurs.
If we want to customize further, we can also pass a request object to the fetch() function. For example, with the following code block, let’s send a POST request and get the response from an operation that sends data to an API.
// Create the request object
var requestOptions = {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name: 'John', age: 30 })
};
// Send the request object and handle the response
fetch('https://api.example.com/endpoint', requestOptions)
.then(response => response.json())
.then(data => {
console.log(data);
})
.catch(error => {
console.log('API hatası: ' + error);
});
In the example above, a request object is created and passed to the fetch() function. This request object specifies a POST request with the method property and sends a Content-Type header with the headers property. It also sends data in JSON format with the body property. Then, the request is sent with the fetch() function and the response is returned as a Promise object. The response is handled with the Promise object’s then() and catch() methods, and the data is processed or an error message is shown.
As shown in this example, you can send a request to an API with JavaScript using the fetch() API and handle the response. However, only a POST request is sent in this example. You can also send other request types with the fetch() API, such as GET, PUT, and DELETE.
Concepts We Use
fetch(): A function in JavaScript used to send an HTTP request and receive the response. This function takes a URL and optionally a request object, and returns aPromiseobject.Promise: An object in JavaScript that represents the result of an operation. A successful result is handled with thethen()method of thePromiseobject, and an error is handled with thecatch()method.then(): A method of thePromiseobject, and it is called when thePromiseresolves. As an argument to this method, it receives the value of the resolvedPromise.catch(): A method of thePromiseobject, and it is called when an error occurs while thePromiseis resolving. As an argument to this method, it receives the error that occurred.XMLHttpRequest: An object in JavaScript used to send an HTTP request and receive the response. This object lets a web page send an HTTP request and receive the response.open(): A method of theXMLHttpRequestobject, and it specifies a request type and URL.send(): A method of theXMLHttpRequestobject, and it sends the request.onload: An event of theXMLHttpRequestobject, and it is called when the response has loaded.status: A property of theXMLHttpRequestobject, and it represents the HTTP status code of the response.responseText: A property of theXMLHttpRequestobject, and it represents the response data as a string.
Fetch API:
XMLHttpRequest:
- Example: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Sending_and_Receiving_Binary_Data
Share it if it helped


