DEV Community

Emmanuelthadev
Emmanuelthadev

Posted on

How to make a HTTP GET Request in JavaScript

To make an HTTP GET request in JavaScript, you can use the XMLHttpRequest object or the fetch() function.

Here's an example of making an HTTP GET request using XMLHttpRequest:


function makeGetRequest(url) {
  const xhr = new XMLHttpRequest();

  xhr.onreadystatechange = function() {
    if (xhr.readyState === XMLHttpRequest.DONE) {
      if (xhr.status === 200) {
        console.log(xhr.responseText);
      } else {
        console.error(xhr.statusText);
      }
    }
  };

  xhr.open('GET', url);
  xhr.send();
}
Enter fullscreen mode Exit fullscreen mode

makeGetRequest('https://www.example.com');
Here's an example of making an HTTP GET request using fetch():


fetch('https://www.example.com')
  .then(response => response.text())
  .then(data => console.log(data))
  .catch(error => console.error(error));
Enter fullscreen mode Exit fullscreen mode

Note that both XMLHttpRequest and fetch() are asynchronous, which means that the code will not wait for the response to complete before continuing to execute. Instead, they provide a way to specify a callback function that will be called when the response is received.

Top comments (0)