How do I make an HTTP request in Javascript

In JavaScript, you can make an HTTP request by using the built-in XMLHttpRequest object or the newer fetch() method.

Here’s an example using XMLHttpRequest:

const xhr = new XMLHttpRequest();‘GET’, ‘’);
xhr.onload = function() {
if (xhr.status === 200) {
} else {
console.log(‘Request failed. Status code: ‘ + xhr.status);

In this example, we’re sending a GET request to the URL When the response is received, the onload function is called. If the response status is 200 (which means it’s successful), we log the response text to the console. If the status code is anything other than 200, we log an error message instead.

Here’s an example using the newer fetch() method:

.then(response => response.text())
.then(data => console.log(data))
.catch(error => console.error(error));

In this example, we’re using the fetch() method to send a GET request to the URL We then use the .then() method to handle the response, converting it to text using the text() method and logging it to the console. If there’s an error, we use the .catch() method to log it to the console.

Note that the fetch() method returns a Promise, so we use the .then() and .catch() methods to handle the response asynchronously.

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *