How do I make an HTTP request in Javascript? - VRGyani News


Friday, February 24, 2023

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's how you can use both:

Using XMLHttpRequest:

const xhr = new XMLHttpRequest();'GET', ''); xhr.onreadystatechange = function() { if (xhr.readyState === 4 && xhr.status === 200) { console.log(xhr.responseText); } }; xhr.send();

Using fetch():

fetch('') .then(response => response.text()) .then(data => console.log(data)) .catch(error => console.error(error));

Both examples above make a GET request to Once the response is received, the first example logs the response as text to the console, while the second example logs the response data as text to the console using Promises.

Note that the fetch() method returns a Promise, which you can use to handle the response asynchronously.

No comments:

Post a Comment

Trending This Week