我想创建一个 Express API 并使用express-validator. 目前这是我的验证中间件
protected validate = async (request: Request, response: Response, next: NextFunction): Promise<void> => {
const validationErrors: Result<ValidationError> = validationResult(request);
if (!validationErrors.isEmpty()) {
response.status(422).json({ errors: validationErrors.array() });
} else {
next();
}
};
我的基本验证设置看起来像
public persist = [
body('username')
.isString()
.withMessage('username must be of type string.')
.isLength({ min: 1 })
.withMessage('username must be at least one character long.')
.exists()
.withMessage('username is required.'),
body('password')
.isString()
.withMessage('password must be of type string.')
.isLength({ min: 1 })
.withMessage('password must be at least one character long.')
.exists()
.withMessage('password is required.'),
this.validate,
];
当我调用POST /users以创建新用户时,我会收到有关无效输入的详细错误响应。当我删除所有自定义错误消息时,我收到此响应
[
{
"msg": "Invalid value",
"param": "username",
"location": "body"
},
{
"msg": "Invalid value",
"param": "password",
"location": "body"
}
]
有没有办法获得自动生成的错误消息,还是我真的必须自己编写这些错误消息?
拉丁的传说
元芳怎么了
相关分类