繁体   English   中英

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

[英]How to validate the request body if the body is a single json array?

我正在尝试使用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.
    }

我如何验证身体?

我按照文档中的说明进行了操作,这是代码:只需在代码中的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
}]

如果您使用的是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); 
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM