Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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,687 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!