Wednesday, February 1, 2023

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 more modern fetch API.

Here's an example of making a GET request using XMLHttpRequest:

javascript
var xhr = new XMLHttpRequest(); xhr.open('GET', 'https://api.example.com/data', true); xhr.onreadystatechange = function() { if (xhr.readyState === XMLHttpRequest.DONE) { if (xhr.status === 200) { console.log(xhr.responseText); } else { console.error(xhr.statusText); } } }; xhr.send();

And here's an example of making a GET request using the fetch API:

javascript
fetch('https://api.example.com/data')
  .then(response => {
    if (!response.ok) {
      throw new Error(response.statusText);
    }
    return response.json();
  })
  .then(data => console.log(data))
  .catch(error => console.error(error));

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home