O'Reilly logo

Node for Front-End Developers by Garann Means

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 with a slash—so let’s look ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required