I'm using node.js and express in my current app. I have created several middleware functions, each one being created like:
function loadUser(req, res, next){
...
}
开发者_如何学运维I'd like to create a middleware that would check the existence of mandatory params in an express action. For instance, I have a /user/create action which needs nickname, password, email, ... as mandatory parameters. I would then need to pass this list of params to a middleware so it can check if those parameters exist in the req.query.
Any idea ?
UPDATE
I've finally done the following (in express documentation, there is an example of middleware that require additional parameter http://expressjs.com/guide.html#route-middleware).
function checkParams(arr){
return function(req, res, next) {
// Make sure each param listed in arr is present in req.query
var missing_params = [];
for(var i=0;i<arr.length;i++){
if(! eval("req.query." + arr[i])){
missing_params.push(arr[i]);
}
}
if(missing_params.length == 0){
next();
} else {
next(JSON.stringify({ "error" : "query error", "message" : "Parameter(s) missing: " + missing_params.join(",") }));
}
}
}
It is then called like the other middlewares:
app.post('/user/create', checkParams(["username", "password"]), function(req, res){
...
});
Have you tried implementing it as a dynamic helper instead of a middleware? It might work.
精彩评论