Default (GPT-3.5)

How do I make an HTTP request in Javascript?

ChatGPTChatGPT

To make an HTTP request in JavaScript, you can use the `XMLHttpRequest` object or the more modern `fetch` API. Here's an example of using both methods:

1. Using XMLHttpRequest:

var xhr = new XMLHttpRequest();
xhr.open("GET", "https://api.example.com/data", true); // The URL and method for the request
xhr.onreadystatechange = function () {
  if (xhr.readyState === 4 && xhr.status === 200) { // Check if response is ready and successful
    var response = JSON.parse(xhr.responseText); // Parse the response as needed
    console.log(response);
  }
};
xhr.send(); // Send the request to the server

2. Using fetch API (modern approach):

fetch("https://api.example.com/data")
  .then(function (response) {
    if (response.ok) {
      return response.json(); // Parse response as JSON if successful
    } else {
      throw new Error("Error: " + response.status);
    }
  })
  .then(function (data) {
    console.log(data);
  })
  .catch(function (error) {
    console.log(error);
});

Both approaches allow you to make GET requests, but they can also be used for other HTTP methods like POST, PUT, DELETE by modifying the parameters accordingly.