我正在尝试使用express-validator
验证请求的正文。孔正文是单个数组,因此我没有字段名称。
我正在使用 express-validator
和 express
版本 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 = 函数(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
}]
关于javascript - 如果请求体是单个 json 数组,如何验证请求体?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48721018/