To make an HTTP request in JavaScript, you can use the built-in XMLHttpRequest
object or the newer fetch
API. Here’s an example of each method:
Using XMLHttpRequest
:
javascriptCopy codevar 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();
Using fetch
:
javascriptCopy codefetch('https://api.example.com/data')
.then(function(response) {
if (response.ok) {
return response.json();
} else {
throw new Error('Error: ' + response.status);
}
})
.then(function(data) {
console.log(data);
})
.catch(function(error) {
console.log(error);
});
In both cases, the examples show how to make a GET request to https://api.example.com/data
. You can modify the URL and the HTTP method (e.g., ‘POST’, ‘PUT’, etc.) according to your needs.
The XMLHttpRequest
approach has been around for a long time and has good browser compatibility, whereas the fetch
API is newer and provides a more modern and streamlined approach for making HTTP requests.