Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Tony Brackins
28,766 PointsFetch()
I'm looking at this video and doing a fetch function of a URL. It returns a "readable stream" but anyone know how to just return the JSON?
1 Answer
Chris Shaw
26,676 PointsHi Tony,
The fetch API has a few different helper methods that are bound to the response prototype but we'll simply focus on the json method. As fetch uses promises to pass data around, we can simply use two then callbacks, one to get the parsed JSON and another to do something else with it.
fetch('/path/to/request')
.then(function(response) {
// Return the response as a JSON object
return response.json();
})
.then(function(json) {
console.log(json);
});
What is happening is we are first waiting for the fetch API to be completed which returns the response stream, then we convert the response value to a JSON object then log that to our console.
Hope that helps.
Tony Brackins
28,766 PointsAwesome, that works! Thanks Chris!
Michael Liendo
15,326 PointsMichael Liendo
15,326 PointsHey Tony, can you share a code snippet?