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 Making a GET Request with http

Why can't I use JSON.parse() method within the http.get callback function?

var http = require("http");
var username = "ryanscharfer";

function playerJSStatus (username, badges, pnts) {
  var message = username + " has " + badges + " badges and "+ pnts+" points in JS.";
  console.log(message);
}



http.get("http://teamtreehouse.com/"+username+".json", function(response){
  //console.log(response.statusCode);
  var data = JSON.parse(response);
  console.log(data);


})

The error I get is:

undefined:1
[object Object]
^
SyntaxError: Unexpected token o
at Object.parse (native)
at ClientRequest.<anonymous> (/home/treehous
at ClientRequest.g (events.js:180:16)
at ClientRequest.emit (events.js:95:17)
at HTTPParser.parserOnIncomingClient [as onI
at HTTPParser.parserOnHeadersComplete [as on
at Socket.socketOnData [as ondata] (http.js:
at TCP.onread (net.js:527:27)

1 Answer

With the http node module, you can't use the response directly in the way you did, as it's not the body of the response that is returned, it is a instance object of the http.ClientRequest class (see the Node.js http.request documentation).

Instead, you need to assemble the response body by listening to the data and end events on the response as it gets streamed through.

The code below should work (I believe this is covered in the course, though perhaps you hadn't gotten up to this stage yet).

var http = require("http");
var username = "ryanscharfer";

function playerJSStatus (username, badges, pnts) {
  var message = username + " has " + badges + " badges and "+ pnts+" points in JS.";
  console.log(message);
}



http.get("http://teamtreehouse.com/"+username+".json", function(response){
  //console.log(response.statusCode);

  var body = '';

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

  response.on('end', function() {
    var data = JSON.parse(body)
    console.log(data);
  });


});