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.
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter