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 newer fetch API. Here are examples of both:

Using XMLHttpRequest:

const xhr = new XMLHttpRequest();
xhr.open('GET', 'https://example.com/api/data');
xhr.onload = () => {
if (xhr.status === 200) {
console.log(xhr.response);
} else {
console.log('Error', xhr.statusText);
}
};
xhr.send();

Using fetch:

fetch('https://example.com/api/data')
.then(response => {
if (response.ok) {
return response.json();
} else {
throw new Error('Error');
}
})
.then(data => console.log(data))
.catch(error => console.error(error));

Note that in the fetch example, we first check if the response is “ok” before calling json() to parse the response data. This is because fetch only rejects the promise on network errors or when a CORS error occurs, but not on HTTP errors like 404 or 500.

--

--

Nikhil Soman Sahu
Nikhil Soman Sahu

Written by Nikhil Soman Sahu

Sr Software Developer | Spring Boot | Flutter | Dart | Java

No responses yet