我尝试使用express-validator在我的Node / Express API中构建参数验证。但是,当我使用以下curl命令curl -X POST -d "foo=bar" http://localhost:3000/collections/test
发出缺少字段(在本例中为name)的POST请求时,请求仍然成功完成,跳过验证。以下是我目前的代码 - 关于为何绕过验证的任何想法?
var util = require('util');
var express = require('express');
var mongoskin = require('mongoskin');
var bodyParser = require('body-parser');
var expressValidator = require('express-validator');
var app = express();
app.use(bodyParser());
app.use(expressValidator());
var db = mongoskin.db('mongodb://@localhost:27017/test', {safe:true})
app.param('collectionName', function(req, res, next, collectionName){
req.collection = db.collection(collectionName)
return next()
});
app.post('/collections/:collectionName', function(req, res, next) {
req.checkBody('name', 'name is required').notEmpty();
req.collection.insert(req.body, {}, function(e, results){
if (e) return next(e)
res.send(results)
});
});
app.listen(3000);
答案 0 :(得分:10)
您需要在处理请求之前添加对任何验证错误的检查。因此,对于您的post
API,您需要将其更新为:
app.post('/collections/:collectionName', function(req, res, next) {
req.checkBody('name', 'name is required').notEmpty();
// check for errors!
var errors = req.validationErrors();
if (errors) {
res.send('There have been validation errors: ' + util.inspect(errors), 400);
return;
}
req.collection.insert(req.body, {}, function(e, results){
if (e) return next(e)
res.send(results)
});
});
有关详细信息,请参阅用法示例:https://github.com/ctavan/express-validator#usage