![]() |
| Foto oleh Markus Spiske: https://www.pexels.com/id-id/foto/kode-pada-lensa-pergeseran-kemiringan-2004161/ |
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/api/endpoint')
.then(data => {
console.log(data);
})
.catch(error => {
console.error(error);
});
Here's the same example using the
fetch API:fetch('https://example.com/api/endpoint')
.then(response => response.json())
.then(data => {
console.log(data);
})
.catch(error => {
console.error(error);
});
The `
fetch` API is generally easier to use and has better support for modern features such as streaming and cancelling requests, but it is not supported in older browsers. If you need to support older browsers, you may need to use a polyfill or fall back to using `XMLHttpRequest`.

إرسال تعليق