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 built-in `XMLHttpRequest` object or the newer `fetch()` API. Here's how to make a simple GET request using both methods:

Using XMLHttpRequest:

var xhr = new XMLHttpRequest();
xhr.open('GET', 'https://api.example.com/data', true);
xhr.onreadystatechange = function() {
  if (xhr.readyState === 4 && xhr.status === 200) {
    var response = JSON.parse(xhr.responseText);
    // handle response data
  }
};
xhr.send();

Using fetch():

fetch('https://api.example.com/data')
  .then(function(response) {
    if (response.ok) {
      return response.json();
    }
    throw new Error('Request failed.');
  })
  .then(function(data) {
    // handle response data
  })
  .catch(function(error) {
    console.log(error);
});

Note that these examples show how to make a basic GET request. You can also customize the requests by adding headers, sending POST/PUT/PATCH requests with request bodies, etc., depending on your specific needs.