How do I make an HTTP request in Javascript?
Feb 17, 2023
You can make an HTTP request in JavaScript using the built-in XMLHttpRequest
object or the newer fetch
method.
Using XMLHttpRequest:
const xhr = new XMLHttpRequest();
xhr.open('GET', 'https://example.com/api/data');
xhr.onload = () => {
if (xhr.status === 200) {
console.log(xhr.responseText);
} else {
console.log('Request failed. Returned status of ' + xhr.status);
}
};
xhr.send();
Using fetch:
fetch('https://example.com/api/data')
.then(response => response.text())
.then(data => console.log(data))
.catch(error => console.error(error));
Both of these methods can be used for GET, POST, PUT, DELETE, and other HTTP methods by changing the first parameter of the open
method or using the method
option in the fetch
call.