How do I make an HTTP request in Javascript?

TechLoons
2 min readJul 16, 2023
Photo by Arnold Francisca on Unsplash

In JavaScript, you can make HTTP requests using the XMLHttpRequest object or the newer fetch API. Here's an example of how you can make an HTTP request using both methods:

Using XMLHttpRequest:

var xhr = new XMLHttpRequest();
xhr.open("GET", "https://api.example.com/data", true);
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
var response = JSON.parse(xhr.responseText);
console.log(response);
}
};
xhr.send();

In the example above, we create a new XMLHttpRequest object, specify the HTTP method (GET in this case) and the URL we want to send the request to. We also set up an onreadystatechange event handler to handle the response when it's received. The readyState property of the XMLHttpRequest object indicates the state of the request, and a value of 4 means the request is complete. We also check that the status property is 200 to ensure that the request was successful before processing the response.

Using the fetch API:

fetch("https://api.example.com/data")
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));

In this example, we use the fetch function, which returns a promise that resolves to the response object. We can then use the .json() method on the response object to extract the JSON data from the response. We use another .then() block to handle the data and log it to the console, and a .catch() block to handle any errors that may occur during the request.

Both methods can be used to make various types of HTTP requests (e.g., GET, POST, PUT, DELETE) by specifying the appropriate method and additional parameters in the request.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

TechLoons
TechLoons

Written by TechLoons

Welcome to TechLoons, your go-to source for the latest tips and information on a wide range of topics.

No responses yet

Write a response