Javascript

How do I make an HTTP request in Javascript?

Less than a minute to read

In Javascript, you can make HTTP requests using the XMLHttpRequest object or by using the fetch API. Here is an example of making a GET request using XMLHttpRequest:

var xhr = new XMLHttpRequest();
xhr.open("GET", "https://www.example.com", true);
xhr.send();

xhr.onreadystatechange = function() {
  if (this.readyState === XMLHttpRequest.DONE && this.status === 200) {
    console.log(this.responseText);
  }
};

And here is an example of making a GET request using fetch:

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

Leave a Reply

Your email address will not be published. Required fields are marked *

Sign up for our Newsletter

Join our newsletter and get resources, curated content, and design inspiration delivered straight to your inbox.

Related Posts