5 ways to make HTTP requests in JavaScript
Here, I'll be discussing how modern JavaScript provides a number of ways to send HTTP requests to remote servers.
Modern JavaScript provides a number of ways to send HTTP requests to remote servers. From the native XMLHttpRequest object to third-party libraries like Axios, having such a varied collection of picks has made requesting and dynamically loading content in web applications more effortless than ever before.
So, in today’s post, we’ll discuss different ways of sending HTTP requests in Javascript. Starting from the native options provided by the language, we’ll look at the following five modules and send different types of HTTP requests with them.
XMLHttpRequest
Fetch
Axios
SuperAgent
Ky
Let's get started!
XMLHttpRequest
XMLHttpRequest is a native API in Javascript that encapsulates the logic of sending HTTP requests without having to refresh a loaded web page (AJAX requests). Even though developers rarely use the XMLHttpRequest directly now, it’s still the building block that works underneath many popular HTTP request modules.
So, understanding how to send requests using the XMLHttpRequest method can help you handle unique use cases if a third-party library doesn’t support it.
Here’s how we can send GET requests and asynchronously retrieve data from a remote API using XMLHttpRequest API:
//create XMLHttpRequest object
const xhr = new XMLHttpRequest()
//open a get request with the remote server URL
xhr.open("GET", "https://world.openfoodfacts.org/category/pastas/1.json")
//send the Http request
xhr.send()
//EVENT HANDLERS
//triggered when the response is completed
xhr.onload = function() {
if (xhr.status === 200) {
//parse JSON datax`x
data = JSON.parse(xhr.responseText)
console.log(data.count)
console.log(data.products)
} else if (xhr.status === 404) {
console.log("No records found")
}
}
//triggered when a network-level error occurs with the request
xhr.onerror = function() {
console.log("Network error occurred")
}
//triggered periodically as the client receives data
//used to monitor the progress of the request
xhr.onprogress = function(e) {
if (e.lengthComputable) {
console.log(`${e.loaded} B of ${e.total} B loaded!`)
} else {
console.log(`${e.loaded} B loaded!`)
}
}
As this example shows, the process of sending a GET request with XMLHttpRequest involves three steps:
Create XMLHttpRequest
Opening the HTTP request of the indented type
Sending the request
Once the request is sent, we can use the event handlers provided by the XMLHttpObject to handle its response. Here, we have used two event handlers:
onload
, onerror
, and onprogress
. It’s important to note here that onerror
method only handles network-level errors related to the request. To identify HTTP errors, we have to check the HTTP status code inside the onload
method specifically.
We can send POST requests with XMLHttpRequest following a similar pattern.
// create XMLHttpRequest object
const xhr = new XMLHttpRequest()
// open a POST request
xhr.open("POST", "/food")
// set content-type header to JSON
xhr.setRequestHeader("Content-Type", "application/json");
// send JSON data to the remote server
xhr.send(JSON.stringify(food))
// Event Handlers
// track data upload progress
xhr.upload.onprogress = function(e) {
console.log(`${e.loaded}B of ${e.total}B uploaded!`)
}
// triggered when data upload is finished
xhr.upload.onload = function(e) {
console.log("Upload completed")
}
// triggered when the response is fully received
xhr.onload = function() {
console.log(xhr.status)
}
// triggered due to a network-level error
xhr.onerror = function() {
console.log("Network error occurred")
}
One main difference between the earlier GET and the current POST request is explicitly setting the content-type headers when posting JSON data. Also, there is an additional event type a POST request can trigger compared to a GET request. They are upload events accessed through the xhr.upload field. These event handlers help us track the data upload progress when the request body has to carry a significant amount of data (e.g., images, files, etc.)
Pros of XMLHttpRequest
Since the method is natively supported, it’s compatible with all modern browser versions.
Removes the need for external dependencies.
Allows accessing and manipulating asynchronous HTTP requests at the base level.
Cons of XMLHttpRequest
The code is verbose and unnecessarily long.
No support for async/await or promise-based syntax.
Most newer HTTP request packages provide simple abstractions over the complex XMLHttpRequest API.