How do I make an HTTP request in Javascript?
In JavaScript, you can make an HTTP request using the XMLHttpRequest object or the newer fetch() function. 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
}
};
xhr.send();
Using fetch():
fetch("https://api.example.com/data")
.then(function (response) {
if (response.ok) {
return response.json();
}
throw new Error("HTTP status code: " + response.status);
})
.then(function (data) {
// Process the data here
})
.catch(function (error) {
// Handle any errors here
console.log("Request failed:", error.message);
});
In both examples, we’re making a GET request to “https://api.example.com/data”. Adjust the URL and HTTP method (GET, POST, etc.) according to your needs. The response is processed in the callback function, where you can access the response data and handle any errors that may occur.
It’s worth noting that the fetch() function provides a more modern and flexible approach for making HTTP requests, but the XMLHttpRequest object is still widely supported in older browsers.