How do I make an HTTP request in Javascript?

How do I make an HTTP request in Javascript

To make an HTTP request in JavaScript, you can use the XMLHttpRequest object or the more modern fetch API.


Here’s an example using XMLHttpRequest:

var xhr = new XMLHttpRequest();

xhr.open(“GET”, “https://example.com”, true);

xhr.onreadystatechange = function() {

  if (xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {

    console.log(xhr.responseText);

  }

};

xhr.send();


And here’s an example using the fetch API:


 fetch(“https://example.com”)

 .then(response => response.text())

 .then(data => console.log(data))

 .catch(error => console.error(error));


Note that in both examples, the response from the server is logged to the console, but you can handle the response data in any way you like.

AI Avenue