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.