This content originally appeared on DEV Community and was authored by DEV Community
Most of the time in your applications, you will need to access data, or "fetch" it from another source, such as a server, API, etc.
This is where fetch requests come in handy.
I'll use this free API about dogs for dummy data.
A fetch request starts out looking like this:
fetch("https://dog.ceo/api/breeds/image/random");
All this does is request the data though; we need some kind of response so we can actually see this data.
fetch("https://dog.ceo/api/breeds/image/random").then((response) => {
});
The response object needs to be translated into a JSON so we are able to use it.
fetch("https://dog.ceo/api/breeds/image/random").then((response) => {
return response.json();
});
Since the json() method also returns a promise, let's return that promise and use another then().
fetch("https://dog.ceo/api/breeds/image/random")
.then((response) => {
return response.json();
})
.then((json) => {
console.log(json);
});
Don't forget to add a catch() method at the end of the series of then() methods to catch any errors for unsuccessful requests.
fetch("https://dog.ceo/api/breeds/image/random")
.then((response) => {
return response.json();
})
.then((json) => {
console.log(json);
})
.catch((err) => {
console.log(err);
});
This content originally appeared on DEV Community and was authored by DEV Community
DEV Community | Sciencx (2022-03-16T19:07:34+00:00) Fetch requests in JavaScript. Retrieved from https://www.scien.cx/2022/03/16/fetch-requests-in-javascript/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.