Javascript Make an HTTP Request

There are several ways to make an HTTP request in JavaScript.

Note: The answer is given by ChatGPT and then slightly modified.

Table of Contents

Fetch API

One of the most popular and widely-used methods is the fetch() API. It is a modern way to make HTTP requests and is supported by most modern browsers. Here's an example of how to use the fetch() API to make a GET request:

  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error(error))

In this example, the fetch() function is used to make a GET request to the specified URL, and the returned promise resolves with a Response object. The json() method is then called on the Response object to parse the response as JSON. The data returned by the json() method is logged to the console.

XML HTTP Request

Another way to make an HTTP request using javascript is using XMLHttpRequest object.

var xhr = new XMLHttpRequest();"GET", "", true);
xhr.onload = function () {

Please note that you may need to handle CORS(Cross-origin resource sharing) if the server you are trying to access are in different domains.