You can make an HTTP request in JavaScript using the XMLHttpRequest
object or the fetch
API.
Using XMLHttpRequest
:
javascriptconst xhr = new XMLHttpRequest();
xhr.open('GET', 'https://example.com/api/data', true);
xhr.onload = function() {
if (xhr.status === 200) {
const response = JSON.parse(xhr.responseText);
console.log(response);
}
};
xhr.onerror = function() {
console.error('Request error');
};
xhr.send();
Using fetch
:
javascriptfetch('https://example.com/api/data')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Fetch error:', error));
Both methods allow you to send requests and handle responses, but the fetch
API is newer and more streamlined, while XMLHttpRequest
is more versatile and supports features like aborting a request.
Comments
Post a Comment