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

JavaScript Node.js Basics (2014) Building a Command Line Application Getting the Response Body

Philip Rurka
Philip Rurka
8,633 Points

undefined body variable

Here is my code.

var username = 'philiprurka';
var https = require('https');

function printMessage(username, badges, points) {
   var message = username + ' has ' + badges + ' total badges and ' + points + 'points in JavaScript.';
   console.log(message);
};

var request = https.get('https://teamtreehouse.com/' + username + '.json', function(response) {
   var body = '';

   response.setEncoding('utf8');

   response.on('data', function(chunk){
      body += chunk;
   });

   response.on('end', function(body){
      console.log('BODY: ' + body);
   });
});


request.on("error", function(error) {
   console.error(error.message);
});

The json link works fine. I have tested it. The problem is that when I run this with node.js, It returns with 'BODY: undefined'. I can't figure out why.

Austin Whipple
Austin Whipple
29,725 Points

Formatted your code block. Be sure to check out the Markdown Cheatsheet link below the text editor for help!

Philip Rurka
Philip Rurka
8,633 Points

Thanks for the heads up. Had no idea! c:

1 Answer

Thomas Nilsen
Thomas Nilsen
14,957 Points
response.on('end', function(body){
      console.log('BODY: ' + body);
   });

remove the 'body' argument from the function. You have already declared it

Philip Rurka
Philip Rurka
8,633 Points

Thanks. It works now. Thumbs up!