在expressjs官网API的app.param讲解中,实现了验证参数的方法:
var express = require('express');
var app = express();
// customizing the behavior of app.param()
app.param(function(param, option) {
return function (req, res, next, val) {
if (val == option) {
next();
}
else {
res.sendStatus(403);
}
}
});
// using the customized app.param()
app.param('id', 1337);
// route to trigger the capture
app.get('/user/:id', function (req, res) {
res.send('OK');
})
app.listen(3000, function () {
console.log('Ready');
})
上例中,入参ID为1337时,才执行到OK.
接着又举出实现参数验证的实现:
var express = require('express');
var app = express();
app.param(function(param, validator) {
return function (req, res, next, val) {
if (validator(val)) {
next();
}
else {
res.sendStatus(403);
}
}
})
app.param('id', function (candidate) {
return !isNaN(parseFloat(candidate)) && isFinite(candidate);
});
// route to trigger the capture
app.get('/user/:id', function (req, res) {
res.send('OK');
})
app.listen(3000, function () {
console.log('Ready');
})
参数只有通过验证,才能执行OK.