How to make an HTTP request in Javascript?
April 28, 2023

In JavaScript, you can make HTTP requests using the built-in XMLHttpRequest
object or the newer fetch()
API. Here’s an example of how to use both methods:
Using XMLHttpRequest:
const xhr = new XMLHttpRequest();
xhr.open('GET', 'https://example.com/api/data');
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
const response = xhr.responseText;
console.log(response);
}
};
xhr.send();
Using fetch():
fetch('https://example.com/api/data')
.then(response => response.text())
.then(data => console.log(data))
.catch(error => console.error(error));
Both methods send an HTTP GET request to the specified URL. You can modify the request method and add headers and request body data as needed. Additionally, you may need to handle errors and parse the response data depending on your use case.