TimesCoding

Learn, Practice, and Excel with our Coding Tutorials!

How to make an HTTP request in Javascript?

January 30, 2023 1 Min read JAVASCRIPT

You can make an HTTP request in JavaScript using the ‘XMLHttpRequest’ or ‘fetch’ API:

Using ‘XMLHttpRequest’:

var xhr = new XMLHttpRequest();
xhr.open("GET", "https://www.example.com", true);
xhr.onreadystatechange = function() {
  if (this.readyState === XMLHttpRequest.DONE && this.status === 200) {
    console.log(this.responseText);
  }
};
xhr.send();

Using ‘fetch’ API:

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