How do I make an HTTP request in Javascript?

How do I make an HTTP request in Javascript?

How to make an HTTP request in JavaScript, you can use the XMLHttpRequest object or the fetch() function.

Here’s an example of using XMLHttpRequest to make a GET request to a JSON API:

const xhr = new XMLHttpRequest();
xhr.open('GET', 'https://api.example.com/endpoint');
xhr.onload = () => {
if (xhr.status === 200) {
// success
const data = JSON.parse(xhr.responseText);
console.log(data);
} else {
// error
console.error(xhr.statusText);
}
};
xhr.onerror = () => {
console.error(xhr.statusText);
};
xhr.send();

Here’s an example of using fetch() to make a GET request to a JSON API:

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

Both XMLHttpRequest and fetch() can be used to make other types of HTTP requests, such as POST, PUT, and DELETE, by setting the method parameter and including a request body as necessary.

Leave a Comment