How do I make an HTTP request in Javascript?

To make an HTTP request in JavaScript, you can use the built-in XMLHttpRequest object or the newer fetch() method. Here’s an example of how to use each method:

Using XMLHttpRequest:

const xhr = new XMLHttpRequest();
xhr.open('GET', 'https://example.com/api/data');
xhr.onload = function() {
  if (xhr.status === 200) {
    console.log(xhr.responseText);
  } else {
    console.log('Request failed.  Returned status of ' + xhr.status);
  }
};
xhr.send();
fetch('https://example.com/api/data')
  .then(response => {
    if (response.ok) {
      return response.text();
    } else {
      console.log('Request failed.  Returned status of ' + response.status);
    }
  })
  .then(data => console.log(data))
  .catch(error => console.error(error));

In both cases, you first specify the HTTP method and URL for the request. For XMLHttpRequest, you then set up an event listener to handle the response once it arrives, whereas with fetch() you use a Promise chain. Note that the second then() block in the fetch() example is where you actually process the response data, after checking that the response was successful with the ok property.

Thanks for reading, let me know if there are any doubts in comment section

Submit a Comment

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

Subscribe

Select Categories