To make an HTTP request in JavaScript,
you can use the XMLHttpRequest
object or the newer fetch
API.
Here's an example of how to use each of them:
Using XMLHttpRequest:
var xhr = new XMLHttpRequest();
xhr.open("GET", "https://api.example.com/data", true);
xhr.onreadystatechange = function() {
if (xhr.status === 200) {
var response = JSON.parse(xhr.responseText);
// Handle the response data here
console.log(response);
}
};
xhr.send();
In this example, we create a new XMLHttpRequest
object and specify the request method (in this case, a GET request) and the URL to which we want to send the request.
We set up an onreadystatechange
event handler to process the response when the request is complete. Finally, we call the send()
method to send the request.
Using fetch API (recommended):
fetch("https://api.example.com/data")
.then(function(response) {
if (response.ok) {
return response.json();
}
throw new Error("HTTP error " + response.status);
})
.then(function(data) {
// Handle the response data here
console.log(data);
}
)
.catch(function(error) {
// Handle any errors here
console.log(error);
});
With the fetch API, we simply call the fetch()
function with the URL as the parameter.
It returns a Promise that resolves to the response. We can use the .then()
method to process the response and extract the JSON data (using response.json()
).
If the response is not successful (e.g., if the server returns an error status), we throw an error. Finally, we can use the .catch()
method to handle any errors that occur during the request.
Both methods allow you to make HTTP requests, but the fetch API provides a more modern and flexible interface for handling network requests.
It is recommended to use the fetch API for new projects or modern browsers.
0 Comments