Member-only story
How To Make An HTTP Request in Javascript, All Methods
5 min readMay 9, 2023
In JavaScript, you can make HTTP requests using the XMLHttpRequest
object or the newer fetch
API. I'll provide examples for both approaches.
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);
// Process the response here
console.log(response);
}
};
xhr.send();
The above example demonstrates a GET request to https://api.example.com/data
. You can replace the URL with the desired API endpoint. The onreadystatechange
function is called whenever the ready state of the request changes. When the ready state is 4
(request completed) and the status is 200
(successful), the response is processed.
Using fetch
API (with Promises)
fetch("https://api.example.com/data")
.then(function(response) {
if (response.ok) {
return response.json();
}
throw new Error("Network response was not OK");
})
.then(function(data) {
// Process the response here
console.log(data);
})
.catch(function(error) {
console.error("Error:", error);
});