-
Book Overview & Buying
-
Table Of Contents
Advanced Express Web Application Development
By :
You will have noticed that we have repeated the id validation in each of our routes. Let's improve things using app.params.
Here is the offending line of code that simply checks to see if our id is a valid MongoDB id:
if (req.params.id.match(/^[0-9a-fA-F]{24}$/) == null)
return res.json(400, 'Bad Request');Let's add a middleware to handle this ./lib/middleware/id.js. We define a validate function that takes four parameters, with the last being the value of id. We then validate the id parameter, returning a 400 Bad Request, if it's invalid. We then call next(), which calls the next middleware in our Express stack:
exports.validate = function(req, res, next, id){
if (id.match(/^[0-9a-fA-F]{24}$/) == null)
return res.json(400, 'Bad Request');
next();
}Now we can use this id middleware in our Express server. Let's include the param middleware and add this line before the first route so that it applies to all of our routes: ./lib/express/index...
Change the font size
Change margin width
Change background colour