How do I make an HTTP request in Javascript
How do I make an HTTP request in Javascript?
You can make an HTTP request in JavaScript using the built-in XMLHttpRequest object or the newer fetch API. Here's an example of how to make a GET request using both methods:
Using XMLHttpRequest
const xhr = new XMLHttpRequest();
xhr.open('GET', 'https://example.com/api/data');
xhr.onload = () => {
if (xhr.status === 200) {
console.log(xhr.responseText);
} else {
console.error('Request failed. Returned status:', xhr.status);
}
};
xhr.send();
Using fetch:
fetch('https://example.com/api/data')
.then(response => {
if (response.ok) {
return response.text();
} else {
throw new Error('Request failed.');
}
})
.then(data => console.log(data))
.catch(error => console.error(error));
Both methods can also be used to make POST requests and other types of requests by modifying the xhr.open() method or the fetch() options.
Comments
Post a Comment