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()` function. Here's how to do it with both approaches:

1. Using XMLHttpRequest:

   var xhr = new XMLHttpRequest();
   xhr.open('GET', 'https://api.example.com/data', true); // Specify the URL and method (GET, POST, etc.)
   
   // Optional: Set request headers
   xhr.setRequestHeader('Content-Type', 'application/json');
   
   // Handle response
   xhr.onload = function() {
     if (xhr.status === 200) { // Successful response status code is 200
       console.log(xhr.responseText); // Response data as text
       var jsonResponse = JSON.parse(xhr.responseText); // Parse JSON response if applicable
       console.log(jsonResponse);
     }
     else {
       console.error('Request failed. Status:', xhr.status);
     }
   };
   
   // Send the request
   xhr.send();

2. Using fetch():

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

Both methods support different types of requests like GET, POST, PUT, DELETE by specifying appropriate parameters in `.open()` for XMLHttpRequest or using additional options in `fetch()`.