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

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

我正在尝试使用 express-validator 验证请求的主体。孔主体是单个数组,所以我没有字段名称。

我正在使用 express-validator 的新 API 和 express 版本 4。

正文是这样的:

["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 版本,我可以实现这种行为。 这是我的请求示例 body: 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();
};

这是我的请求示例 body:

[{
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); 
});