How do I make an HTTP request in Javascript?

In JavaScript, you can make an HTTP request using the XMLHttpRequest object or the fetch() function. Here are examples of how to use both:

Using XMLHttpRequest:

const xhr = new XMLHttpRequest();
xhr.open('GET', 'https://example.com/api/data');
xhr.send();

xhr.onload = function() {
  if (xhr.status === 200) {
    console.log(xhr.responseText);
  } else {
    console.log('Request failed. Returned status of ' + xhr.status);
  }
};


Using fetch:

fetch('https://example.com/api/data')
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error(error));

In the fetch example, response.json() is used to parse the response as JSON. You can use other methods like response.text() or response.blob() depending on the type of response you’re expecting.