You can make an HTTP request in JavaScript using the built-in XMLHttpRequest object or the newer fetch API. Here are examples of how to make GET requests using each method:
Using XMLHttpRequest:
const xhr = new XMLHttpRequest();
xhr.open('GET', 'https://api.example.com/data');
xhr.onload = function() {
if (xhr.status === 200) {
console.log(xhr.responseText);
}
else {
console.log('Request failed. Returned status of ' + xhr.status);
}
};
xhr.send();
using fetch:
fetch('https://api.example.com/data')
.then(response => response.text())
.then(data => console.log(data))
.catch(error => console.log(error));
In both cases, replace https://api.example.com/data with the URL of the endpoint you want to request. The fetch API is generally considered to be more modern and easier to use than XMLHttpRequest, but both methods are still widely used.
Using XMLHttpRequest:
const xhr = new XMLHttpRequest();
xhr.open('GET', 'https://api.example.com/data');
xhr.onload = function() {
if (xhr.status === 200) {
console.log(xhr.responseText);
}
else {
console.log('Request failed. Returned status of ' + xhr.status);
}
};
xhr.send();
using fetch:
fetch('https://api.example.com/data')
.then(response => response.text())
.then(data => console.log(data))
.catch(error => console.log(error));
In both cases, replace https://api.example.com/data with the URL of the endpoint you want to request. The fetch API is generally considered to be more modern and easier to use than XMLHttpRequest, but both methods are still widely used.
Comments
Post a Comment