Posts

Showing posts with the label How to make an HTTP request in Javascript

How do I make an HTTP request in Javascript?

Image
There are several ways to make an HTTP request in JavaScript, the most common being using the XMLHttpRequest or fetch API. Using XMLHttpRequest: var xhr = new XMLHttpRequest(); xhr.open("GET", "http://example.com", true); xhr.onreadystatechange = function() { if (xhr.readyState === 4 && xhr.status === 200) { console.log(xhr.responseText); } }; xhr.send();   Using fetch: fetch("http://example.com") .then(response => response.text()) .then(data => console.log(data)) .catch(error => console.log(error));   Both of these examples make a GET request to "https://example.com". You can replace it with the URL you want to make a request to.