使用Express-Validator验证POST参数

Anc*_*nia 5 javascript api node.js express express-validator

我正在尝试使用express-validator在我的Node/Express API中构建参数验证.但是,当我使用以下curl命令发出缺少字段(在本例中为name)的POST请求时curl -X POST -d "foo=bar" http://localhost:3000/collections/test,请求仍然成功完成,跳过验证.以下是我目前的代码 - 为什么验证被绕过的任何想法?

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);
Run Code Online (Sandbox Code Playgroud)

dyl*_*nts 10

在处理请求之前,您需要添加对任何验证错误的检查.因此,对于您的postAPI,您需要将其更新为:

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)
  });
});
Run Code Online (Sandbox Code Playgroud)

有关更多信息,请参阅用法示例:https://github.com/ctavan/express-validator#usage