【发布时间】:2021-07-21 17:39:48
【问题描述】:
我正在验证密码的验证器页面。
exports.userSignupValidator = (req, res, next) => {
// check for password
req.check('password', 'Password is required').notEmpty();
req.check('password')
.isLength({ min: 6 })
.withMessage('Password must contain at least 6 characters')
.matches(/\d/)
.withMessage('Password must contain a number');
// check for errors
const errors = req.validationErrors();
// if error show the first one as they happen
if (errors) {
const firstError = errors.map(error => error.msg)[0];
return res.status(400).json({ error: firstError });
}
// proceed to next middleware
next();
};
我在其中定义注册路由并将 userSignupValidation 作为中间件来验证密码的路由页面。
router.post("/signup", userSignupValidator, async(req, res) => {
const {name, email, password} = req.body;
try{
await User.findByCredentials(name, email, password);
const user = new User({
name,
email,
password
})
await user.save();
res.send({message: "Successfully Registered"});
}
catch(e){
res.status(422).send({error: e.message});
}
})
为什么我得到 req.check 不起作用。
【问题讨论】:
-
你用的是什么版本?对于较新版本的
check和类似版本,需要/从express-validator导入,而不是从请求中执行。 -
我正在使用新版本,但我不知道 req.check 在 express-validator 的第 6 版中不起作用。兄弟,你能写出适用于第 6 版 express-validator 的整个代码吗?
-
查看文档,根据文档更新代码,如果有问题我可以尝试帮助解决。