To make an HTTP request in Javascript
You can use the built-in XMLHttpRequest
object or the newer fetch()
method. Here are examples of both:
Using XMLHttpRequest:
javascriptvar xhr = new XMLHttpRequest();
xhr.open('GET', 'http://example.com/api/data', true);
xhr.onload = function() {
if (this.status === 200) {
console.log('Success!', this.response);
} else {
console.error('Error:', this.statusText);
}
};
xhr.onerror = function() {
console.error('Network Error');
};
xhr.send();
Using fetch():
javascriptfetch('http://example.com/api/data')
.then(function(response) {
if (response.ok) {
return response.json();
}
throw new Error('Network response was not ok.');
})
.then(function(data) {
console.log('Success!', data);
})
.catch(function(error) {
console.error('Error:', error);
});
In both cases, you need to specify the URL of the resource you want to access. For XMLHttpRequest
, you also need to specify the HTTP method (e.g. GET, POST, etc.) and whether the request should be asynchronous or not. The onload
and onerror
callbacks are used to handle the response and any errors that might occur.
For fetch()
, you use the Promise API to handle the response and errors. The ok
property of the response object is used to check if the request was successful, and the json()
method is used to extract the response body as a JSON object.