To make an HTTP request in JavaScript, you can use the XMLHttpRequest object or the newer fetch API. Here's an example of both methods:
Using XMLHttpRequest:
javascriptvar 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, XMLHttpRequest is used to send a GET request to "https://api.example.com/data". The onreadystatechange function is called whenever the readyState of the request changes. When the readyState is 4 (indicating the request is complete) and the status is 200 (indicating a successful response), the response is parsed and logged to the console.
Using fetch API (recommended):
javascriptfetch("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) {
console.log(data);
})
.catch(function(error) {
console.log("Error:", error);
});
In this example, the fetch function is used to send a GET request to "https://api.example.com/data". It returns a Promise that resolves to the response object. We can check if the response was successful using the ok property, and if so, we parse the response as JSON. Finally, the data is logged to the console. If there was an error during the request or response, it is caught and logged in the catch block.
Both methods allow you to perform various types of requests (GET, POST, PUT, DELETE, etc.) by specifying the appropriate method and additional parameters if needed.