How do I make an HTTP request in Javascript?
Date: 2023-03-25 14:34:48
In Javascript, you can make an HTTP request using the built-in XMLHttpRequest
object or the newer fetch
API.
Here's an example of making an HTTP GET request 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.log('Request failed. Returned status of ' + xhr.status);
}
};
xhr.send();
Here's an example of making an HTTP GET request using the fetch
API:
fetch('https://example.com/api/data')
.then(response => response.text())
.then(data => console.log(data))
.catch(error => console.error(error));
These examples show how to make a GET request, but you can also make other types of requests such as POST, PUT, DELETE, etc. by changing the method in the open
function.