Making an HTTP request in JavaScript
To make an HTTP request in JavaScript using the fetch()
function or the XMLHttpRequest
(XHR) object.
Here’s an example of using fetch()
it to make an HTTP GET request:
fetch('https://example.com/data.json')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));
In this example, we are making an HTTP GET request to the URL https://example.com/data.json
. The fetch()
the function returns a Promise that resolves to a Response object. We then use the json()
method on the Response object to extract the JSON data from the response. Finally, we log the data to the console.
Here’s an example of using the XMLHttpRequest
Object to make an HTTP GET request:
const xhr = new XMLHttpRequest();
xhr.open('GET', 'https://example.com/data.json');
xhr.onload = function() {
if (xhr.status === 200) {
const data = JSON.parse(xhr.responseText);
console.log(data);
} else {
console.error('Request failed. Status code: ' + xhr.status);
}
};
xhr.send();
In this example, a new XMLHttpRequest object is created, and a GET request is sent to the URL https://example.com/data.json. The onload attribute is then assigned to a callback function invoked after completing the request. Checking whether the status code is 200 (OK) in the callback function, we parse the JSON data using JSON. parse() the data and report it to the console. An error message is sent to the console if the response status code is not 200. The request is then sent using the send() function.