How can you make an HTTP request in javascript using the built-in fetch API or using older XMLHttpRequest (XHR) object
- Get link
- X
- Other Apps
You can make an HTTP request in JavaScript using the built-in fetch
API or using the older XMLHttpRequest
(XHR) object.
Here's an
example using fetch
:
fetch('https://api.example.com/data')
.then(response =>
{
if (!response.ok)
{
throw new
Error('Network response was not ok');
}
return
response.json();
})
.then(data => {
console.log(data);
})
.catch(error => {
console.error('There was a problem with the fetch operation:', error);
}); This code sends a GET request to 'https://api.example.com/data'
. When the response
is received, it checks if the response was successful (response.ok
). If it was, it
parses the response as JSON and logs it to the console. If there was an error,
it throws an error and logs it to the console.
Here's an
example using XHR:
const xhr = new XMLHttpRequest();
xhr.open('GET', 'https://api.example.com/data');
xhr.onload = function() {
if (xhr.status ===
200) {
const data =
JSON.parse(xhr.responseText);
console.log(data);
} else {
console.error('There was a problem with the XHR request.');
}
};
XMLHttpRequest
object and opens a GET
request to 'https://api.example.com/data'
. When the response is
received, it checks if the status is 200
(OK). If it is, it parses
the response as JSON and logs it to the console. If there was an error, it logs
an error message to the console. Finally, it sends the request.
- Get link
- X
- Other Apps
Comments
Post a Comment