To make an HTTP request in JavaScript, you can use the XMLHttpRequest
object or the newer fetch
API. Here’s an example using XMLHttpRequest
:
function makeRequest(method, url) {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.open(method, url);
xhr.onload = function () {
if (this.status >= 200 && this.status < 300) {
resolve(xhr.response);
} else {
reject({
status: this.status,
statusText: xhr.statusText
});
}
};
xhr.onerror = function () {
reject({
status: this.status,
statusText: xhr.statusText
});
};
xhr.send();
});
}
makeRequest('GET', 'https://example.com')
.then(data => {
console.log(data);
})
.catch(error => {
console.error(error);
});
Here’s an example using the fetch
API:
fetch('https://example.com')
.then(response => response.text())
.then(data => {
console.log(data);
})
.catch(error => {
console.error(error);
});
Both examples make a GET request to the specified URL and log the response to the console. The fetch
API is generally easier to use and has better support for streaming and handling errors, but XMLHttpRequest
is still widely used and supported.