我是NodeJS和Express的新手,我想验证API参数。 现在我通过以下方式验证参数:
if(!req.body.parametername)
return res.send({"message": "Please provide parametername"});
if(!req.body.parametername)
return res.send({"message": "parametername can not be blank"});
但我希望回复如下:
{
"username": [
"This field is required."
],
"password": [
"This field can not be blank."
]
}
如果参数无效或未提供,这是我想要的响应。
答案 0 :(得分:1)
您可能会在这里找到express-validator。 特别是本节:
req.assert('email', 'required').notEmpty();
req.assert('email', 'valid email required').isEmail();
req.assert('password', '6 to 20 characters required').len(6, 20);
var errors = req.validationErrors(); // Or req.asyncValidationErrors();
var mappedErrors = req.validationErrors(true); // Or req.asyncValidationErrors(true);
mappedErrors将如下所示:
{
email: {
param: "email",
msg: "valid email required",
value: "<received input>"
},
password: {
param: "password",
msg: "6 to 20 characters required",
value: "<received input>"
}
}