Dynamic routing
In the very first recipe of this cookbook, Setting up a router, we explored various ways to set up routing in Node. Express provides a far superior and very powerful routing interface which we'll explore in this recipe.
Getting ready
We'll be working with our nca
folder.
How to do it...
Let's say we want to add a page for a fictional character by the name of Mr Page. We'll name the route page
, so in the routes
section of app.js
we add the following code:
app.get('/page', function (req, res) { res.send('Hello I am Mr Page'); });
We can also define flexible routes, and grab the requested route using req.params
, like so:
app.get('/:page', function (req, res) { res.send('Welcome to the ' + req.params.page + ' page'); });
It's okay to throw our callbacks directly into app.get
while developing, but in the interest of a clutter-free app.js
let's take our callbacks and load them from routes/index.js
as follows:
exports.index = function(req, res){ res.render('index', { title: 'Express...