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 trialAkshay Bhamare
15,616 PointsAccessing the response argument as an object
Hi, I don't understand that after getting a response in the get method as an object why are we still again creating a new object by parsing data in JSON?? How the argument(response) is different than the profile object ??
2 Answers
Miguel Barra
6,855 PointsWhen you perform
response.on('data', data => {
// here we get the data as a buffer object
}
what you get is the data (the response) as a buffer. A buffer is not legible to human eyes so you need to parse it to a string object. Then, in the end callback method you parse the string response into a JSON object
response.on('end', () => {
// Parse the data
const profile = JSON.parse(body);
// Print the data
printMessage(username, profile.badges.length, profile.points.JavaScript);
});
And to claritfy, to access the body of the response you need to use response.on('nameofthecalback'...
Pepe ToΓ±o
13,815 PointsIn practice, get method just returns a response in JSON format by default; However, I think the TreeHouse API endpoint (https://teamtreehouse.com/username.json) returns a kind of custom JSON object where is needed to format de chunk of data