How do I make an HTTP request in Javascript?

 
 
 

In JavaScript, you can make an HTTP request using the built-in XMLHttpRequest object or the newer fetch API. Here are some examples of how to use these methods:

Using XMLHttpRequest:

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

Using fetch:

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

Both methods can be used to make requests with different HTTP methods (e.g. GET, POST, PUT, DELETE), and can also be configured with headers and request payloads if needed.

Leave A Reply