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();
xhr.open(‘GET’, ‘https://example.com/data.json’);
xhr.onload = function() {
if (xhr.status === 200) {
console.log(xhr.responseText);
} else {
console.log(‘Request failed. Status code: ‘ + xhr.status);
}
};
xhr.send();

In this example, we’re sending a GET request to the URL https://example.com/data.json. 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:

fetch(‘https://example.com/data.json’)
.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 https://example.com/data.json. 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 *