Sitemap

How do I make an HTTP request in Javascript?

1 min readMar 9, 2023

In JavaScript, you can make an HTTP request using the built-in fetch API or the XMLHttpRequest (XHR) object. Here are examples of how to use both methods:

Using fetch:

fetch('https://example.com/data')
.then(response => response.json())
.then(data => {
// Handle the response data
console.log(data);
})
.catch(error => {
// Handle errors
console.error(error);
});

The fetch function takes a URL as an argument and returns a Promise that resolves to a Response object. You can then use the json() method on the Response object to extract the response data as JSON.

Using XMLHttpRequest:

const xhr = new XMLHttpRequest();

xhr.onreadystatechange = function() {
if (xhr.readyState === XMLHttpRequest.DONE) {
if (xhr.status === 200) {
const data = JSON.parse(xhr.responseText);
// Handle the response data
console.log(data);
} else {
// Handle errors
console.error(xhr.status);
}
}
};

xhr.open('GET', 'https://example.com/data');
xhr.send();

With XHR, you create a new XMLHttpRequest object, set the onreadystatechange property to a callback function that will be called when the request state changes, and then call the open and send methods on the object to make the request. In the callback function, you can check the readyState and status properties of the XMLHttpRequest object to determine the state of the request and handle the response accordingly.

--

--

Nagaraj Gurusamy
Nagaraj Gurusamy

Written by Nagaraj Gurusamy

Data Analyst | Full Stack Developer | FreeLancer | Digital Marketing | Entrepreneur | Tiger Paw Intelectual |

No responses yet