How do I make an HTTP request in Javascript

To make an HTTP request in JavaScript, you can use the XMLHttpRequest object or the more modern fetch function.

Here is an example using XMLHttpRequest to make a GET request to the JSONPlaceholder API to retrieve a list of posts:


const xhr = new XMLHttpRequest();

xhr.responseType = 'json';

xhr.onreadystatechange = function () {
if (xhr.readyState === XMLHttpRequest.DONE) {
console.log(xhr.response);
}
}

xhr.open('GET', 'https://jsonplaceholder.typicode.com/posts');

xhr.send();

Here is an example using fetch to make the same request:


fetch('https://jsonplaceholder.typicode.com/posts')
.then(response => response.json())
.then(data => console.log(data));