Almost any web application serves more than a single resource. So now we know how to serve content using an HTTP server; but how do we handle multiple resources? Routing is the name of the game. We need to understand the incoming request and map it to the appropriate request handler. This is a bit more complicated than the previous example, so we will build it step by step, improving it with every step.
To demonstrate the routing of requests, let us build a simple application that serves two resources at /start
and /finish
, displaying Hello and Goodbye respectively. To simplify the code, we will serve plain text. So before anything else, let's take a look at the code:
var http = require("http"); var url = require("url"); function onRequest(request, response) { var pathname = url.parse(request.url).pathname; console.log("Request for " + pathname + " received."); if(pathname === "/start"){ response.writeHead(200, {"Content-Type": "text/plain"}); response...