Introduction
To make an HTTP request in Javascript, you can use the built-in XMLHttpRequest object or the newer fetch() method.
Here are examples of how to use each:
Using XMLHttpRequest
// create a new XMLHttpRequest object
const xhr = new XMLHttpRequest();
// define the HTTP method, URL, and async flag
xhr.open('GET', 'https://example.com/data.json', true);
// set any headers (optional)
xhr.setRequestHeader('Content-Type', 'application/json');
// define a callback function to handle the response
xhr.onload = function() {
if (xhr.status === 200) {
console.log(xhr.responseText);
} else {
console.error('Request failed. Returned status of ' + xhr.status);
}
};
// send the request
xhr.send();
Using fetch()
fetch('https://example.com/data.json', {
method: 'GET',
headers: {
'Content-Type': 'application/json'
}
}).then(response => {
if (!response.ok) {
throw new Error('Request failed');
}
return response.json();
}).then(data => {
console.log(data);
}).catch(error => {
console.error(error);
});
Learn more here, How to Use XMLHttpRequest in JavaScript?