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();'GET', '');
xhr.onload = function() {
  if (xhr.status === 200) {
  } else {
    console.log('Request failed.  Returned status of ' + xhr.status);
  .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 *


Select Categories