How do I make an HTTP request in Javascript?

Estimated read time 1 min read

To make an HTTP request in JavaScript, you can use the built-in XMLHttpRequest object or the newer fetch API. Here’s an example of both methods:

Using XMLHttpRequest:

var xhr = new XMLHttpRequest();
xhr.open("GET", "https://api.example.com/data", true);
xhr.onreadystatechange = function () {
  if (xhr.readyState === 4 && xhr.status === 200) {
    var response = JSON.parse(xhr.responseText);
    console.log(response);
  }
};
xhr.send();

Using fetch API:

fetch("https://api.example.com/data")
  .then(function(response) {
    if (response.ok) {
      return response.json();
    } else {
      throw new Error("Error: " + response.status);
    }
  })
  .then(function(data) {
    console.log(data);
  })
  .catch(function(error) {
    console.log(error);
  });

In both examples, we are making a GET request to https://api.example.com/data and handling the response. You can replace the URL with the endpoint you want to request.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply