make an HTTP request in Javascript

To make an HTTP request in Javascript, you can use the fetch() API, which is a modern way to make asynchronous requests, or the XMLHttpRequest (XHR) object, which is an older method for making asynchronous requests.

Example using fetch():

fetch('https://example.com/data')

  .then(response => response.json())

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

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

Example using XHR:

const xhr = new XMLHttpRequest();
xhr.open('GET', 'https://example.com/data', true);
xhr.onload = function() {
  if (this.status === 200) {
    console.log(this.response);
  } else {
    console.error(this.statusText);
  }
};
xhr.onerror = function() {
  console.error(this.statusText);
};
xhr.send();

Post a Comment

0 Comments