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 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);
  });


});