How do I make an HTTP request in Javascript?

You can make an HTTP request in JavaScript using the XMLHttpRequest or the fetch API.

Using XMLHttpRequest:

var xhr = new XMLHttpRequest();
xhr.open(‘GET’, ‘https://example.com/api/data’, true);
xhr.onload = function() {
if (xhr.status === 200) {
console.log(xhr.responseText);
}
else {
console.log(‘Request failed. Returned status of ‘ + xhr.status);
}
};
xhr.send();

 

How do I make an HTTP request in Javascript?

 

How do I make an HTTP request in Javascript?

 

Using fetch:

fetch(‘https://example.com/api/data’)
.then(response => {
if (response.ok) {
return response.text();
} else {
throw new Error(‘Network response was not ok’);
}
})
.then(data => console.log(data))
.catch(error => console.error(‘Error:’, error));

Leave a Comment