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 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
}
Alex Ball
Alex Ball
Courses Plus Student 12,673 Points

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