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 User Route

Brian Patterson
Brian Patterson
19,588 Points

Getting this error. events.js:160 throw er; // Unhandled 'error' event

I am getting the following error and can't work out why. Below is my code:

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

}
/*
## Handle HTTP route GET /:username i.e. /chalkers

*/
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");
    response.write(username + "\n");
    response.end('Footer\n');



  }
}

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

Below is the error I am getting.

Server running at http://<workspace-url>/
events.js:160
      throw er; // Unhandled 'error' event
      ^

Error: write after end
    at ServerResponse.OutgoingMessage.write (_http_outgoing.js:439:15)
    at Object.user (/Users/katypatterson/Dropbox/JavaScript/simple_node_site/router.js:24:14)
    at Server.<anonymous> (/Users/katypatterson/Dropbox/JavaScript/simple_node_site/app.js:37:10)
    at emitTwo (events.js:106:13)
    at Server.emit (events.js:191:7)
    at HTTPParser.parserOnIncoming [as onIncoming] (_http_server.js:546:12)
    at HTTPParser.parserOnHeadersComplete (_http_common.js:99:23)

1 Answer

Neil McPartlin
Neil McPartlin
14,662 Points

Hi Brian. You are just missing a pair of curly braces inside the 'home' function. These should surround the code block that follows the 'if' statrement like so.

function home(request, response) {
    //  - if url == "/" && GET
    if(request.url === "/")  { // <-- { ADDED HERE
      //show search
      response.writeHead(200, {'Content-Type': 'text/plain'});
      response.write("Header\n");
      response.write("Search\n");
      response.end('Footer\n');
    } // <-- AND HERE
}

Thanks for this Neil! I totally missed when he added the IF Statement to that Home route.