【问题标题】:node.js routes validate json bodynode.js 路由验证 json 正文
【发布时间】:2014-07-11 12:20:40
【问题描述】:

我正在使用 express、body-parser 和 moongose 使用 Node.js 构建一个 RESTful Web 服务。我在 POST 请求的正文中获取 json 数据,该函数如下所示:

router.route('/match')
// create a match (accessed at POST http://localhost:3000/api/match)
.post(function(req, res) {
    if (req._body == true && req.is('application/json') == 'application/json' ) {
        var match = new Match();        // create a new instance of the match model
        match.name = req.body.name;  // set the match name and so on...
        match.host = req.body.host;
        match.clients = req.body.clients;
        match.status = req.body.status;
        // save the match and check for errors
        match.save(function(err) {
            if (err) {
                //res.send(err);
                res.json({ status: 'ERROR' });
            } else {
                res.json({ status: 'OK', Match_ID: match._id });    
            }
        });
    } else {
        res.json({ status: 'ERROR', msg: 'not application/json type'});
    }
});

我用于在数据库中存储匹配项的模型如下所示:

// app/models/match.js
var mongoose     = require('mongoose');
var Schema       = mongoose.Schema;
var MatchSchema   = new Schema({
    name:       String,
    host:       String,                                     
    clients:    { type: [String]},
    date:       { type: Date, default: Date.now },
    status:     { type: String, default: 'started' }
});

module.exports = mongoose.model('Match', MatchSchema);

但是如何验证 POST 请求正文中的 json 数据是否具有我想要的键/值字段?为了澄清起见,我不想在不完整的数据库中插入数据。如果我测试跳过 json 数据中的键/值对,我会在数据库中得到一个缺失的字段,当我尝试在我的代码中读取 req.body.MISSING_FIELD 参数时,我会得到未定义。模型中除日期外的所有字段都是必需的。

我正在使用这样的 json 字符串在数据库中添加匹配项

{"name": "SOCCER", "host": "HOST_ID1", "clients": ["CLIENT_ID1", "CLIENT_ID2"], "status": "started"}

【问题讨论】:

  • 你为什么不把它们变成必需的? name: {type: String, required: true}.
  • 谢谢 Ben,适合大多数部分,但我仍然可以输入一个空数组(客户端)
  • 对不起,我的错。现在它起作用了。我有客户:{ type: [{type: String, required: true}]} 但客户:{ type: [{type: String, required: true}], required: true} 解决了我的问题。谢谢!
  • 任何人都知道如何捕获格式错误的 json 数据并返回错误消息,如果我发送格式错误的 json 数据,我会收到“SyntaxError: Unexpected token”
  • 在 try/catch 块中执行。

标签: json node.js express mongoose


【解决方案1】:

我使用了一个非常简单的函数,它接受一个键数组,然后循环遍历它并确保 req.body[key] 不是一个假值。然而,修改它以仅容纳未定义的值是微不足道的。

在 app.js 中

app.use( (req, res, next ) => {
    req.require = ( keys = [] ) => {
         keys.forEach( key => {
             // NOTE: This will throw an error for ALL falsy values.
             // if this is not the desired outcome, use
             // if( typeof req.body[key] === "undefined" )
             if( !req.body[key] )
                 throw new Error( "Missing required fields" );
         })
    }
})

在您的路由处理程序中

try{

    // Immediately throws an error if the provided keys are not in req.body
    req.require( [ "requiredKey1", "requiredKey2" ] );

    // Other code, typically async/await for simplicity

} catch( e ){
    //Handle errors, or
    next( e ); // Use the error-handling middleware defined in app.js
}

这仅检查以确保主体包含指定的键。 IT 不会验证以任何有意义的方式发送的数据。这对我的用例来说很好,因为如果数据完全无用,那么我将只处理 catch 块中的错误并将 HTTP 错误代码返回客户端。 (考虑发送一个有意义的有效载荷)

如果您想以更复杂的方式验证数据(例如,确保电子邮件格式正确等),您可能需要查看验证中间件,例如 https://express-validator.github.io/docs/

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-03-03
    • 2018-01-18
    • 2014-12-03
    • 1970-01-01
    • 1970-01-01
    • 2021-05-06
    • 2020-10-10
    • 2012-05-27
    相关资源
    最近更新 更多