TL;DR: This post is about URL parameters and routing in Express.js, and it’s an excerpt (Chapter 6) from my new book Pro Express.js: Master Express.js—The Node.js Framework For Your Web Development. The book was released this week (~December 24, 2014), but we have a great limited-time offer for you which will be announced on Sunday, December 28, 2014 on Webapplog.com. This post is the last post in the series of excerpts from Pro Express.js with other posts as follow: Error Handling and Running an Express.js App, Express.js Security Tips, LoopBack 101: Express.js on Steroids, Sails.js 101 and Secret Express.js Settings.
To review, the typical structure of an Express.js app fig(which is usually a server.js
or app.js
file) roughly consists of these parts, in the order shown:
-
Dependencies : A set of statements to import dependencies
-
Instantiations : A set of statements to create objects
-
Configurations : A set of statements to configure system and custom settings
-
Middleware : A set of statements that is executed for every incoming request
-
Routes : A set of statements that defines server routes, endpoints, and pages
-
Bootup : A set of statements that starts the server and makes it listen on a specific port for incoming requests
This chapter covers the fifth category, routes and the URL parameters that we define in routes. These parameters, along with the app.param() middleware, are essential because they allow the application to access information passed from the client in the URLs (e.g., books/proexpressjs
). This is the most common convention for REST APIs. For example, the http://hackhall.com/api/posts/521eb002d00c970200000003
route will use the value of 521eb002d00c970200000003
as the post ID.
Parameters are values passed in a query string of a URL of the request. If we didn’t have Express.js or a similar library, and had to use just the core Node.js modules, we’d have to extract parameters from an HTTP.request
object via some require('querystring').parse(url)
or require('url').parse(url, true)
function “trickery.”
Let’s look closer at how to define a certain rule or logic for a particular URL parameter.
Continue reading “URL Parameters and Routing in Express.js”