How do I make an HTTP request in Javascript?

 How do I make an HTTP request in Javascript?




To make an HTTP request in JavaScript, you can use the XMLHttpRequest object or the newer fetch() function. Here's an example using XMLHttpRequest:

function sendRequest() { const xhr = new XMLHttpRequest(); xhr.onreadystatechange = function() { if (xhr.readyState === 4 && xhr.status === 200) { console.log(xhr.responseText); } }; xhr.open('GET', 'http://example.com', true); xhr.send(); }

Here's an example using fetch():

fetch('http://example.com') .then(response => response.text()) .then(text => console.log(text)) .catch(error => console.error(error));

Both examples make a GET request to the URL http://example.com and log the response to the console.


Post a Comment

Previous Post Next Post