How do I make an HTTP request in Javascript?

How do I make an HTTP request in Javascript?

 Method 1:

To make an HTTP request in JavaScript, you can use the XMLHttpRequest object or the newer fetch() API. Here's an example using XMLHttpRequest:


var xhr = new XMLHttpRequest();

xhr.open('GET', 'http://www.example.com/', true);

xhr.onload = function() {
  if (this.status == 200) {
    // Do something with the data
  }
};

xhr.send();

Here's the same example using the fetch() API:


fetch('http://www.example.com/')
  .then(response => response.text())
  .then(data => {
    // Do something with the data
  });

Both examples make an HTTP GET request to the specified URL and execute a callback function with the response data. The fetch() method is easier to use and more flexible, but not all browsers support it yet. You can check if the fetch() method is supported by the user's browser with this code:


if (!window.fetch) {
  // Use XMLHttpRequest instead
}

Method 2:

To make an HTTP request in JavaScript, you can use the XMLHttpRequest object or the more modern fetch() function. Here is an example of how to use fetch() to make a GET request to retrieve data from a URL:


fetch('https://www.example.com/data.json')
  .then(response => response.json())
  .then(data => {
    // Do something with the data
    console.log(data);
  });

This will send a GET request to the specified URL and, if the request is successful, the server's response will be parsed as JSON and passed to the then() function as an object. You can then use the data in that object to do whatever you need to do with it.

If you have any question let me know in the comment.