如果正文是单个json数组,如何验证请求体?

时间:2018-02-10 12:56:43

标签: javascript node.js express express-validator

我正在尝试使用express-validator来验证请求的正文。这个漏洞是一个单独的数组,因此我没有字段名称。

我使用的是express-validatorexpress版本4的新API。

身体看起来像这样:

["item1","item2"]

我的代码:

app.post('/mars/:Id/Id', [
    check('id')
        .isLength({  max: 10 })

    .body() //try many ways to get the body. most examples i found were for the old api
    .custom((item) => Array.isArray(item))
],
    (req, res, next) => {           
       const data: string = matchedData(req); //using this method to only pass validated data to the business layer
       return controller.mars(data); //id goes in data.id. i expect there should be an data.body once the body is validated too.
    }

我如何验证身体?

2 个答案:

答案 0 :(得分:0)

我按照文档的说明做了,这是代码: 只需在代码中的expressValidator引用之后声明自定义验证器。

app.use(expressValidator());
app.use(expressValidator({
    customValidators: {
        isArray: function(value) {
            return Array.isArray(value);
        }
    }
}));
之后,您可以检查有效性:

req.checkBody('title', 'title é obrigatório').notEmpty();
req.checkBody('media','media must be an array').isArray();

我在我的项目中使用版本3.2.0,我可以实现这种行为。 以下是我的请求正文的示例:     exports.validateAddArrayItem = function(req,res,next){     {     标题:' foo',     媒体:[1,2,3]     }

如果您不想更改您的回复,我曾经做过类似的验证:

if (req.body.constructor === Array) {
        req.body[0].employee_fk = tk.employee_id;
    }
    req.assert('item', 'The body from request must be an array').isArray();

    var errors = req.validationErrors();
    if (errors) {
        var response = { errors: [] };
        errors.forEach(function(err) {
            response.errors.push(err.msg);
        });
        return res.status(400).json(response);
    }
    return next();
};

这是我的请求正文的一个例子:

[{
employeefk: 1,
item: 4
}]

答案 1 :(得分:0)

如果您使用的是ajax,请尝试将您的数组放在如下所示的对象中:

$.ajax({
    type: "POST",
    url: url,
    data: { arr: ["item1", "item2"] },
    success: function (data) {
        // process data here
    }
});

现在您可以使用arr标识符来应用验证规则:

const { check, body, validationResult } = require('express-validator/check');

...

app.post('/mars/:Id/Id', [
    check('chatId').isLength({  max: 10 }),
    body('arr').custom((item) => Array.isArray(item))
], (req, res, next) => {           
       const data: string = matchedData(req); 
       return controller.mars(data); 
});