Table of contents
APIs, or Application Programming Interfaces, are mechanisms that allow two software components to communicate with each other using a set of definitions and protocols. APIs often provide API keys to developers to ensure that data is accessed securely and only by authorized users.
Before the fetch()
API, web developers used XMLHttpRequest
(XHR) to send asynchronous requests. Let’s explore how XHR works and how it compares to the modern fetch()
API.
XMLHttpRequest (XHR)
XMLHttpRequest
is an API that allows web pages to make HTTP requests to servers. It is commonly used in AJAX (Asynchronous JavaScript and XML) programming.
Also before fetch(), we used to send XMLHttpRequest, here we also have some constructors, for eg:
XMLHttpRequest.readyState
XMLHttpRequest.response
Let's have a look at XMLHttpRequest.readyState:
Value | State | Description |
0 | UNSENT | Client has been created. open() not called yet. |
1 | OPENED | open() has been called. |
2 | HEADERS_RECEIVED | send() has been called; headers and status are available. |
3 | LOADING | Downloading; responseText holds partial data. |
4 | DONE | The operation is complete. |
Understanding these states:
0 (UNSENT): The request has not been sent yet. The client has been created, but
open()
has not been called.1 (OPENED): The request has been sent, but data has not been received.
2 (HEADERS_RECEIVED): Headers have been received, but the status of the data received is unknown. (something is received but we don't know what is received)
3 (LOADING): The response is being received. Partial data is available.
4 (DONE): The operation is complete. Data can be checked and used.
Example of XMLHttpRequest
Consider this HTML boilerplate with js code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body style="background-color: #212121;">
</body>
<script>
const requestURL = "https://api.github.com/users/HarshCodesX";
const xhr = new XMLHttpRequest();
xhr.open('GET', requestURL); // State changed to 1 (OPENED)
console.log(xhr.readyState); // Logs: 1
// Continuously track the state
xhr.onreadystatechange = function() { //as many time state is changing, function is also being called again n again
console.log(xhr.readyState); // Logs state changes
if (xhr.readyState === 4) { // DONE
const data = JSON.parse(this.responseText); //most of the time data is received in the form of string
console.log(data);
console.log(typeof data); // Logs: object
console.log(data.followers);
}
};
xhr.send();
</script>
</html>
Explanation of the Code:
- Initialize and Open Request:
const requestURL = "https://api.github.com/users/HarshCodesX";
const xhr = new XMLHttpRequest();
xhr.open('GET', requestURL); //open() takes 2 argument
The XMLHttpRequest
object is created, and the request is opened using the open()
method with the GET
method and the specified URL. The state changes to 1 (OPENED).
- Log Initial State:
console.log(xhr.readyState);
// outputs: 1 as shown in above image
- Track State Changes:
xhr.onreadystatechange = function() { ... }
This function will be called whenever the readyState
changes. Inside the function, the current readyState
is logged.
- Handle Response:
if (xhr.readyState === 4) {
const data = JSON.parse(this.responseText);
console.log(data);
console.log(typeof data); // Logs: object
console.log(data.followers);
}
When the readyState
is 4 (DONE), the response is fully received. The response text is parsed into a JavaScript object using JSON.parse(this.responseText)
. The data is then logged, including the type and the number of followers.
- Send Request:
xhr.send();
The request is sent to the server.
Summary
State 0 (UNSENT): The
XMLHttpRequest
object is created. The initial state is0
.The
open('GET', requestURL)
method initializes a GET request to the specified URL.State 1 (OPENED): After calling
open()
, the state changes to1
. The request has been initialized, butsend()
has not been called yet.State 2 (HEADERS_RECEIVED): After calling
send()
, the browser sends the request to the server. Once the server responds with headers, the state changes to2
. The status and headers of the response are now available.State 3 (LOADING): As the browser starts receiving the response body, the state changes to
3
. This state indicates that the response is being downloaded, and partial data may be available.State 4 (DONE): When the entire response has been received and the operation is complete, the state changes to
4
. The response data can now be processed.