In this blog post we will see some advanced routing techniques to be used with express
`
In my previous blog post I discussed basics of routes and how to implement them. In this section we will some more route features
[js]
//app.js file
var users = require(‘./routes/users’);
app.use(‘/users’, users);
//users.js file
//this route will be called for all request with /users only
//i.e http://127.0.0.1:3000/users
router.get(‘/’, function (req, res) {
res.send(‘Route For Users Base URL’);
});
//this route will be called for /users/list
//i.e http://127.0.0.1:3000/users/list
router.get(‘/list’, function (req, res) {
res.send(‘List Route’);
});
//this will be called for /list/1 or /list/2
//there is a regex for the parameter to number only
//so for urls like /list/manish this route won’t be called
router.get(/^/list/(d+)$/, function (req, res) {
console.log(req.params);
res.send(‘list route for number id ‘ + req.params[0]);
});
//this route will be called all urls with /list and the other part will be treated as //request parameter
//e.g http://127.0.0.1/list/manish will pass in this route with parameter as manish
//but url http://127.0.0.1/list/manish/test won’t match this
router.get(‘/list/:id’, function (req, res) {
res.send(‘List Route For ID ‘ + req.param(‘id’));
});
//this is called when a form is submitted on /users/list url
router.post(‘/list’, function (req, res) {
var post = JSON.stringify(req.body);
res.send(‘Route For Post ‘ + post);
});
//this is to perform a 301 redirect
router.get(‘/list/users/access’, function (req, res) {
res.redirect(301, ‘/list/access’);
});
router.get(‘/list/access’, function (req, res) {
res.send(‘Access Page After Redirect’);
});
[/js]
Using route.param for validation per-processing
Another extension of routes is to use the param() function to perform some validaion or per-processing logic.
This can be used to load objects, validations etc.
[js]
router.param(‘id’, function (req, res, next, id) {
if (id % 2 == 0) {
next(new Error(‘Only Odd Values Allowed’));
} else {
req.is_valid = 1;
next();
}
});
router.get(‘/list/:id’, function (req, res) {
//param is called for this as well only once
res.send(‘List Route For ID ‘ + req.param(‘id’));
});
router.get(‘/list/:id/:page’, function (req, res) {
//param is called for this as well only once
res.send(‘List Route For ID ‘ + req.param(‘id’) + " page " + req.param(‘page’) + ‘ Is valid request ‘ + req.is_valid);
});
[/js]