HTTP Request in JavaScript

PHOTO EMBED

Sun Feb 19 2023 01:56:51 GMT+0000 (Coordinated Universal Time)

Saved by @jasonuk

How do I make an HTTP request in Javascript?
To make an HTTP request in JavaScript, you can use the built-in XMLHttpRequest object or the newer fetch() API.

Using XMLHttpRequest:

scss
Copy code
const xhr = new XMLHttpRequest();
xhr.open('GET', 'https://example.com/api/data');
xhr.onreadystatechange = function() {
  if(xhr.readyState === 4 && xhr.status === 200) {
    console.log(xhr.responseText);
  }
};
xhr.send();
Using fetch():

javascript
Copy code
fetch('https://example.com/api/data')
  .then(response => response.text())
  .then(data => console.log(data))
  .catch(error => console.error(error));
Note that fetch() returns a Promise that resolves to a Response object. You can call the .json() method on the response object if you expect the data to be in JSON format instead of text. Additionally, make sure to handle errors appropriately by using .catch() method or by adding an error handling function in the onreadystatechange event for XMLHttpRequest.
content_copyCOPY

https://chat.openai.com/chat