How do I make an HTTP request in Javascript?
- User
How do I make an HTTP request in Javascript?
- Assistant
To make an HTTP request in JavaScript, you can use the built-inXMLHttpRequestobject or the newerfetch()function. Here's an example of how to use both methods:
Using XMLHttpRequest:
────────────────────────────────────────────────────────────────────
javascriptCopy codevar xhr = new XMLHttpRequest(); xhr.open("GET", , true); // Specify the HTTP method and the URL xhr.onreadystatechange = function() { if (xhr.readyState === 4 && xhr.status === 200) { // Check if the request has been completed successfully var response = xhr.responseText; // Retrieve the response console.log(response); } }; xhr.send(); // Send the request
Using fetch():
────────────────────────────────────────────────────────────────────
javascriptCopy codefetch() .then(function(response) { if (response.ok) { // Check if the response was successful return response.text(); // Retrieve the response as text } else { throw new Error("Error: " + response.status); } }) .then(function(data) { console.log(data); // Process the response data }) .catch(function(error) { console.log(error); // Handle any errors });
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.