Routing and Receiving Data from a Path

Routing is another thing we can get from middleware, but it’s nothing so complicated that we couldn’t implement it ourselves if we had to. Routing will let us extract data from a URL’s path in addition to its querystring. A route usually defines, at minimum, the method of the request, the pattern the route matches, and a callback function to be executed when a matching request is received. It’s pretty simple to check those things, although we’d need to add robustness for a real-world application.

Let’s say we want our application above, instead of checking for a first and last name in the querystring, to look for them in the path of the URL. Let’s say also that this functionality lives on its own virtual “page”, sayHello, and we’ll pass in parameters like /sayHello/first name/last name:

var http = require("http"),
  url = require("url"); 
  
http.createServer(function(req, res) {
  // split out parts of the path
  var path = url.parse(req.url).pathname.split("/");
  // handle GET requests to /sayHello/
  if (req.method == "GET" && path[1] == "sayHello") {
    var userName = path[2] + " " + path[3],
      html = "<!doctype html>" +
        "<html><head><title>Hello " + userName + "</title></head>" +
        "<body><h1>Hello, " + userName + "!</h1></body></html>";
      
    res.end(html);
  }
}).listen(8000);

Of course, that’s a somewhat fragile and non-scalable way to deal with routing—for example, we have to dump the first element in our path array since our path starts ...

Get Node for Front-End Developers now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.