How do I make an HTTP request in Javascript?
You can make an HTTP request in JavaScript using the built-in XMLHttpRequest object or the newer fetch API. Here's an example using both methods:
Using XMLHttpRequest:
Copy code
const xhr = new XMLHttpRequest(); xhr.open('GET', 'https://api.example.com/data'); xhr.onload = function() { if (xhr.status === 200) { console.log(xhr.responseText); } else { console.error('Request failed. Returned status of ' + xhr.status); } }; xhr.send();
Using fetch:
Copy code
fetch('https://api.example.com/data') .then(response => { if (!response.ok) { throw new Error('Network response was not ok'); } return response.text(); }) .then(data => console.log(data)) .catch(error => console.error('Error:', error));
Both methods are useful, but the fetch API is generally considered to be easier to use and more modern. However, XML Http Request still has some advantages in certain situations, such as the ability to monitor upload progress.













