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 Build a Simple Dynamic Site with Node.js Handling Routes in Node.js Populating User Information

Values showing as undefined and I can't figure out why

My home router works completely fine, but for some reason, my user router is displaying this error

response.write(values.username + "has " + values.badges + " badges \n");

I've looked over my code and tried many different things out but nothing seems to be working. Please help

function user(request, response) {
  // if the url == "/..."
  var username = request.url.replace("/", "");
  if (username.length > 0) {
    response.setHeader('Content-Type', 'text/plain');
    response.statusCode = 200;
    response.write("Header\n");

    // get json from Treehouse
    var studentProfile = new Profile(username);

    studentProfile.on("end", function(profileJSON) {
      // Store the values which we need
      var values = {
        avatarUrl: profileJSON.gravatar_url,
        username: profileJSON.profile_name,
        badges: profileJSON.badges.length,
        javascriptPoints: profileJSON.points.JavaScript
      }
    });

    response.write(values.username + "has " + values.badges + " values.badges \n");
    response.end("Footer\n");

    // on "error"
    studentProfile.on("error", function(error) {
      response.end("Footer\n"); 
    });
  }
}

1 Answer

Steven Parker
Steven Parker
231,236 Points

The code that creates "values" is inside the handler for the "end" event, but the code trying to reference it is outside of that function (and thus the variable is out of scope).

If you look at the video, you'll see that the code that references the variable is inside the same function as where it is created.

Oh... wow. Thanks as always Steven. I really struggle to notice some things!