gpt4 book ai didi

node.js - 自定义响应消息,用于验证 Node js 中的所有必需参数

转载 作者:太空宇宙 更新时间:2023-11-03 22:12:06 26 4
gpt4 key购买 nike

我是 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."
]
}

如果参数无效或未提供,这就是我想要的响应。

最佳答案

您可能会找到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>"
}
}

关于node.js - 自定义响应消息,用于验证 Node js 中的所有必需参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39346886/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com