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 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
218,692 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!