How do I make an HTTP request in Javascript?

To make an HTTP request in Javascript, you can use the built-in XMLHttpRequest object or the fetch API. Here are examples of both approaches:

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.error(Request failed. Status: ${xhr.status});
}
};
xhr.send();

Using fetch:

fetch(‘https://example.com/api/data’)
.then(response => {
if (response.ok) {
return response.text();
}
throw new Error(Request failed. Status: ${response.status});
})
.then(data => {
console.log(data);
})
.catch(error => {
console.error(error);
});

Both examples demonstrate making a GET request to the URL https://example.com/api/data . However, you can also make other types of HTTP requests such as POST, PUT, DELETE, etc. by modifying the request method and the request body as needed.

4 Likes