How do I make an HTTP request in Javascript?

Posted on

In JavaScript, you can make HTTP requests using the built-in fetch API or the older XMLHttpRequest (XHR) API. Here’s an example of how to make an HTTP GET request using the fetch API:

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

This code sends a GET request to https://example.com/data and logs the response data to the console as a JSON object. If there’s an error, it will be logged to the console as well.

HTTP request

Here’s an example of how to make an HTTP GET request using the XMLHttpRequest API:

const xhr = new XMLHttpRequest();
xhr.open('GET', 'https://example.com/data');
xhr.onload = function() {
  if (xhr.status === 200) {
    const data = JSON.parse(xhr.responseText);
    console.log(data);
  } else {
    console.error('Request failed. Status:', xhr.status);
  }
};
xhr.onerror = function() {
  console.error('Request failed. Network error.');
};
xhr.send();

This code also sends a GET request to https://example.com/data, but it uses the XMLHttpRequest API instead. The onload function checks the response status and logs the response data to the console if it’s successful, or logs an error message if it’s not. The onerror function logs an error message if there’s a network error.

Leave a Reply

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