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!

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

error handling in "populating user information" is _not_ working.

Hello Andrew Chalkley, et al.,

i have been going through this very good course by @chalkers on object oriented JavaScript and enjoying it, but hit a major snag in the error handling it says should work if you put an incorrect name in the .../[username] of the URL. or any other user name beside "chalkers." it throws an unexpected error if any other name, "joykesten2," "davemcfarland," or even mine, "faddah," is used.

here is my code, which i believe i copied along exactly as @chalkers was showing it in the video and i was followig along in my treehouse workspace —

my index.html —

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <title>Treehouse Profile</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <style type="text/css" media="screen">
        @import url(http://fonts.googleapis.com/css?family=Varela+Round);
        @import url(http://necolas.github.io/normalize.css/3.0.2/normalize.css);

        body {
            background: #ECEEEF;
            text-align: center;
            margin: 100px auto;
            max-width: 462px;
            padding: 0 40px;
            font: 18px normal 'Varela Round', Helvetica, serif;
            color: #777B7E;
        }

        img {
            width: 100%;
        }

        #searchIcon, #avatar {
            width: 50%;
            border-radius: 50%;
            margin: 0 25% 0 25%;
        }

        input {
            font-family: 'Varela Round', Helvetica, serif;
            font-size: 18px;
            padding: 31px 0;
            margin: 10px 0;
            text-align: center;
            width: 360px;
            border-radius: 4px;
            border: 1px solid #D5DDE4;
            color: #2C3238;
        }

        #username {
            margin: 20px 0 0;
        }

        .button {
            border-color: #5FB6E1;
            background: #5FB6E1;
            color: #fff;
        }

        #error {
            width: 100%;
            padding: 22px 0;
            background: #FFE6B2;
            color: #C5A14E;
            position: absolute;
            left: 0;
            top: 0;
        }

        #profile {
            background: #fff;
            border-radius: 4px;
            border: 1px solid #D5DDE4;
            padding: 40px 0 0;
            margin: -40px 0 0;
        }

        ul {
            list-style-type: none;
            padding: 0;
            margin: 40px 0 0;
        }

        li {
            display: inline-block;
            width: 100%;
            padding: 22px 0;
            margin: 0;
            border-top: 1px solid #D5DDE4;
        }

        a, a:visited {
            color: #5FB6E1;
            text-decoration: none;
        }

        span {
            color: #2C3238;
        }
    </style>
</head>
<body><img src="http://i.imgur.com/VKKm0pn.png" alt="Magnifying Glass" id="searchIcon">

<form action="/" method="POST">
    <input type="text" placeholder="Enter a Treehouse username" id="username" name="username">
    <input type="submit" value="search" class="button">
</form></body>
</html>

my app.js —

var router = require("./router.js");
// Problem: We need a simple way to look at a user's badge count and JavaScript points from a web browser.
// Solution: Use Node.js to perform the profile lookups and serve our templates via HTTP.

// Create a web server.
var http = require('http');
http.createServer(function (request, response) {
  router.home(request, response);
  router.user(request, response);
}).listen(3000);
console.log('Server up & running at http://<workspace-url>/');


// Function that handles reading of files and merge in values
  // read from file and get a string (history)
    // merge details into template

my router.js (thus far) —

var Profile = require("./profile.js");

// Handle HTTP route GET / and POST / i.e. Home
function home(request, response) {
  // if url === "/" && GET
  if(request.url === "/") {
    // show search field
    response.writeHead(200, {'Content-Type': 'text/plain'});
    response.write("Header\n");
    response.write("Search\n");
    response.end("Footer\n");
  }
}
  // if url === "/" && POST
    // redirect to /:username

// Handle HTTP route GET /:username i.e., /chalkers, /davemcfarland, /faddah, etc.
function user(request, response) {
  // if url === "/...."
  var username = request.url.replace("/", "");
  if(username.length > 0) {
    response.writeHead(200, {'Content-Type': 'text/plain'});
    response.write("Header\n");

    //get json from Treehouse
    var studentProfile = new Profile(username);
    // on "end"
    studentProfile.on("end", function(profileJSON){; 
      // show profile

      // Store the values which we need
      var values = {
        avatarURL: profileJSON.gravatar_url,
        username: profileJSON.profile_name,
        badges: profileJSON.badges.length,
        javascriptPoints: profileJSON.points.JavaScript
      }
      // Simple response
      response.write(values.username + " has " + values.badges + " badges.\n");
      response.end("Footer\n");      
    });

    // on "error"
    studentProfile.on("error", function(error){  
      // show error
      response.write(error.message + "\n");
      response.end('Footer\n');
    });
  }
}

module.exports.home = home;
module.exports.user = user;

so the regualr routing works fine for the home page, looks like this —

http://port-3000-76v76v5n47.treehouse-app.com

screen shot of normal, working plain url return

if i run this and preview it in my browser, it works fine for "chalkers" on the end of the url, as in —

http://port-3000-76v76v5n47.treehouse-app.com/chalkers

screen shot of working url with "chalkers" return

however, if i use any other valid user name, like "davemcfarland," "joykesten2," or mine, "faddah," or even if i use any other random word to test the error handling, this error gets thrown in the console of the treehouse workspace for the node.js web server and it quits —

treehouse:~/workspace$ node app.js                                                    
Server up & running at http://<workspace-url>/                                        
events.js:85                                                                          
      throw er; // Unhandled 'error' event                                            
            ^                                                                         
Error: write after end                                                                
    at ServerResponse.OutgoingMessage.write (_http_outgoing.js:413:15)                
    at Profile.<anonymous> (/home/treehouse/workspace/router.js:39:16)                
    at Profile.emit (events.js:107:17)                                                
    at IncomingMessage.<anonymous> (/home/treehouse/workspace/profile.js:38:36)       
    at IncomingMessage.emit (events.js:129:20)  
    at _stream_readable.js:908:16                                                     
    at process._tickCallback (node.js:355:11) 
treehouse:~/workspace$     

and of course, now my browser can't connect any more and return the data in the url, as the node.js server just quits.

any idea what is going on here?

also, a number of people in this forum on this particular course module have asked about just exactly where the data is being pulled from, but have been rebuffed with not helpful URLs to docs on AJAX and jQuery. that is not the question they are asking. the question they, and i, are asking, is just where is this specific data for "chalkers" or "davemcfarland" or "faddah" being pulled from? we ask because there seems to be no indication in the code of a URL or other datasource it is being pulled from, it just suddenly shows up as being put into the objectJSON var. is it because it's a treehouse works space and the treehouse web site API automatically? is it something else? what if we had to pull data for a source that is not all ready on our specific server? please explain where/how this specific API data on treehouse users is being pulled from?

thank you in advance.

best,

— faddah portland, oregon, u.s.a.

2 Answers

Andrew Chalkley
STAFF
Andrew Chalkley
Treehouse Guest Teacher

Apparently everything was operational. Maybe it was a ; or { out of place making the error handling not work. The line that starts studentProfile.on("error" should do the handling, if node doesn't see it it could've been a syntax error somewhere. It's just one of those things!

well, o.k., Andrew Chalkley. i'll just mark this one as answered, don't know what it was. i didn't change any code between last night when i was so frustrated and today in the late morning (11 am PST or so) when it just worked, so i don't know. but it's working now, so moving on. thank you for responding.

best,

— faddah

 portland, oregon, u.s.a.
Andrew Chalkley
STAFF
Andrew Chalkley
Treehouse Guest Teacher

How weird!

Can you create a snapshot of the workspace for me and share the link?

Regards,
Andrew

well, unfortunately (or fortunately) Andrew Chalkley, now it's working! i have no idea why. i can confirm i was getting this error i posted above ^^^^^ in the console of the node running app.js over and over again any time i tried any username but yours, @chalkers —

treehouse:~/workspace$ node app.js                                                    
Server up & running at http://<workspace-url>/                                        
events.js:85                                                                          
      throw er; // Unhandled 'error' event                                            
            ^                                                                         
Error: write after end                                                                
    at ServerResponse.OutgoingMessage.write (_http_outgoing.js:413:15)                
    at Profile.<anonymous> (/home/treehouse/workspace/router.js:39:16)                
    at Profile.emit (events.js:107:17)                                                
    at IncomingMessage.<anonymous> (/home/treehouse/workspace/profile.js:38:36)       
    at IncomingMessage.emit (events.js:129:20)  
    at _stream_readable.js:908:16                                                     
    at process._tickCallback (node.js:355:11) 
treehouse:~/workspace$    

i have no idea why other names are working now and the error reporting is working where all it would do before was cause the node server trace error. i swear, it happened all last night until about 2 a.m. as i was fooling around with it. could you maybe check with treehouse IT and see if there was a problem with the web server or what controls the workspaces last night?

best,

— faddah

portland, oregon, u.s.a.