HTTP Request in Javascript

By | 2022-12-21

There are several ways to make an HTTP request in JavaScript. One of the most common ways is using the XMLHttpRequest (XHR) object, which is supported by all modern browsers.

Here’s an example of how to use XMLHttpRequest to send a GET request to retrieve a JSON file from a server:

const xhr = new XMLHttpRequest();

xhr.open('GET', 'https://example.com/data.json');
xhr.onload = function() {
  if (xhr.status === 200) {
    console.log(xhr.responseText); // the response text is the JSON file
  } else {
    console.error('An error occurred: ', xhr.statusText);
  }
};
xhr.send();

Alternatively, you can use the fetch() function, which is a modern way to make HTTP requests and is supported by most modern browsers.

Here’s an example of how to use fetch() to send a GET request to retrieve a JSON file from a server:

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

Both XMLHttpRequest and fetch() allow you to make other types of HTTP requests, such as POST, PUT, and DELETE, as well as specify request headers and send data in the request body.

Author: dwirch

Derek Wirch is a seasoned IT professional with an impressive career dating back to 1986. He brings a wealth of knowledge and hands-on experience that is invaluable to those embarking on their journey in the tech industry.

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.