Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.


  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint
Share this Page URL
Help

Chapter 3. Interaction with the Client > Routing and Receiving Data from a Path

3.2. 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);


  

You are currently reading a PREVIEW of this book.

                                                                                        

Get instant access to over
$1 million worth of books and videos.

  

Start a Free Trial