In the first part of this tutorial we looked at reading a document from CouchDB and keeping our markup separate from our code using Haml templates. We arrived at the point where we clicked on a link, but nothing happened. Today we are going to put that right with some very simple routing.

The URL Module

The basis of all routing is the URL. Fortunately, Node has some basic functions which handle reading the URL so we can then decide what the user is actually trying to do.

If you test this out you should see the relevant text displayed in the standard output.

Subscribe to the mailing list

If you are enjoying this post, please consider signing up to the mailing list.

Tidy up Existing Code

Now we have a basic router telling us that it has detected which page the user wants to display, but is then displaying the default page regardless. To correct this we need to put our existing code within a function and then call that function in the relevant part of the switch statement.

So, create a new (sub) function called display_root() in the main bulk of the http.createServer() function, expecting a url, a server request object and aserver response object as parameters:

function display_root(url, req, res){
...
}

Within the body of the function, you want to insert the main bulk of the application that we wrote last time. I have included the complete code at the bottom of this tutorial, and all code is of course on GitHub.

Now call this function within the switch statement:

display_root(url_parts.pathname, req, res);

Handling Missing Pages

As said, Chromium is looking for a favicon.ico file, but currently this application doesn’t have one. As such it needs to be able to handle missing files gracefully, with the correct 404 response.

Create a new function within the main bulk of the http.createServer() function:

function display_404(url, req, res){
res.writeHead(404,{'Content-Type':'text/html'});
res.write("&lt;h1&gt;404 Not Found&lt;/h1&gt;");
res.end("The page you were looking for: "+url+" can not be found");}

Notice that we have specified the header to be 404.

Now you can call this from within the switch:

display_404(url_parts.pathname, req, res);

You can test it out by going to http://127.0.0.1:8000/qwerty
You should see:

404 Not Found
The page you were looking for: /qwerty can not be found

We could use a Haml template to move the content out of the code, but for the purposes of this tutorial it will suffice.

The Form

Now we want to generate a “Create” page – which will be a form allowing us to enter a list name and 1-5 items. (Note: I have changed from 10 items to 5 for no other reason that I am lazy, and don’t particularly want 10 things on my list, also it keeps the code a bit more clean!)

First, create the Haml template that will be used. We’ll keep this very simple for now. The key part is the form generation. After some trial and error, this mark-up seemed to work: