
In JavaScript, you can make an HTTP request using the built-in XMLHttpRequest object or the more modern fetch API. I’ll show you examples for both methods:
Using XMLHttpRequest:
javascript
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 data here
console.log(response);
}
};
xhr.send();
This code sends a GET request to the specified URL (https://api.example.com/data). When the response is received and its status is 200 (OK), the onreadystatechange callback is triggered, and you can process the response.
Using the fetch API (more modern and recommended :
javascript
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 data here
console.log(data);
})
.catch(function(error) {
// Handle any errors that occurred during the request
console.log(error);
});
The fetch function returns a promise that resolves to the Response object. You can use the ok property of the Response object to check if the request was successful. If it was, you can call the json() method on the Response object to parse the response data as JSON.
These examples demonstrate how to make a simple GET request, but you can also make other types of requests (e.g., POST, PUT, DELETE) by specifying additional parameters in the open method or the fetch function.