2014-06-14 20 views
3

我試圖使用express-validator將參數驗證構建到我的Node/Express API中。但是,當我使用以下curl命令curl -X POST -d "foo=bar" http://localhost:3000/collections/test發出缺少字段(本例中爲名稱)的POST請求時,請求仍會成功完成,從而跳過驗證。以下是我目前的代碼 - 關於爲什麼驗證被繞過的任何想法?使用Express-Validator驗證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); 

回答

8

您需要在處理請求之前添加對任何驗證錯誤的檢查。因此,對於你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

+0

這奏效了 - 沒有意識到錯誤邏輯是'req.checkBody'後需要。謝謝! – Anconia