How do I make an HTTP request in Javascript?

deepak chandra
Feb 17, 2023

--

You can make an HTTP request in JavaScript using the built-in XMLHttpRequest object or the newer fetch method.

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.log('Request failed. Returned status of ' + xhr.status);
}
};
xhr.send();

Using fetch:

fetch('https://example.com/api/data')
.then(response => response.text())
.then(data => console.log(data))
.catch(error => console.error(error));

Both of these methods can be used for GET, POST, PUT, DELETE, and other HTTP methods by changing the first parameter of the open method or using the method option in the fetch call.

--

--

deepak chandra
deepak chandra

Written by deepak chandra

I am a developer and designer from India🇮🇳. I have a passion for programming and designing. I'd call myself a Jack of all trades but master of none.

No responses yet