How do I make an HTTP request in Javascript?

In Development 

By equasar

on Mon Jun 26 2023

To make an HTTP request in JavaScript, you can use the built-in XMLHttpRequest object or the newer fetch API. Here’s an example of 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();

Using fetch:

fetch("https://api.example.com/data")
.then(function(response) {
if (response.ok) {
return response.json();
} else {
throw new Error("Error: " + response.status);
}
})
.then(function(data) {
console.log(data);
})
.catch(function(error) {
console.log(error);
});

Both methods allow you to specify the HTTP method (GET, POST, etc.), the URL you want to request, and handle the response. The fetch API is generally considered more modern and has a simpler syntax, but XMLHttpRequest is still widely supported in older browsers.

Remember to replace “https://api.example.com/data” with the actual URL you want to request.