问题描述
对不起,标题不好,不知道该怎么说。目前正在学习node.js,但我遇到以下问题。
我使用边缘模板框架。我将快速验证用作中间件。
所有内容仍然运行良好-但是如何再次将用户输入发送/恢复到字段中,以及如何将错误提示为用户信息?
这是我目前的代码:
// Registration POST request
router.post('/register',userController.verifyRegister,userController.checkUserExists,userController.registerUser,authController.login
);
...
userController.js
... some code before ...
exports.verifyRegister = async (req,res,next) => {
req.sanitizeBody('username');
req.checkBody('username','Username should not be empty!').notEmpty();
req.sanitizeBody('email');
req.checkBody('email','Email should not be empty').notEmpty();
req.checkBody('email','You must enter a valid email to register').isEmail();
req.checkBody('password','Password should not be empty').notEmpty();
req.checkBody('password-confirm','Password confirmation should not be empty').notEmpty();
req.checkBody('password-confirm','Both passwords does not match!').equals(req.body.password);
const errors = req.validationErrors();
if(errors) {
console.log(errors);
//res.json(req.body.errors); //tried - no work?!?!
res.redirect('back')
return;
}
next();
}
// Check if the user already exists Will hook it up later
... works if all inputs are correct!! ...
任何想法如何?
谢谢。
ps:我正在寻找一个与我一起在git上共同成长的人。我想学习git以及如何通过git开发一个小型应用程序。谢谢。
解决方法
verifyRegister()
是异步的,因此它返回一个Promise。但是,您不会await
来访问request.validationErrors(),因此您的if检查不会返回true。
exports.verifyRegister = async (req,res,next) => {
...
const errors = await req.validationErrors();
if(errors) {
console.log(errors);
return res.redirect('back');
}
next();
}
如果此答案可以帮助您解决问题,请考虑接受或作为有效答案。谢谢。