我有一个简单的注册表格如下:
<div class ="container form">
<div class="jumbotron form"><h2><i class="fa fa-user-plus" aria-hidden="true"></i> Signup</h2></div>
<form action = "/register" method="POST">
<div class="form-group">
<i class="fa fa-user" aria-hidden="true"></i>
<label for="username">Username</label>
<input type = "text" class = "form-control" placeholder = "Enter username" name="username">
</div>
<div class="form-group">
<i class="fa fa-key" aria-hidden="true"></i>
<label for="password1">Password</label>
<input id="password1" type = "password" class ="form-control" placeholder = "Enter password" name="password1">
</div>
<div class="form-group">
<i class="fa fa-key" aria-hidden="true"></i>
<label for="password2">Confirm password</label>
<input id="password2" type = "password" class ="form-control" placeholder = "Enter password" name = "password">
</div>
<div class="form-group">
<i class="fa fa-picture-o" aria-hidden="true"></i>
<label for="img">Image</label>
<input type = "text" class ="form-control" placeholder = "Enter image URL" name = "image">
</div>
<button id="submit-login" type ="submit" class="btn btn-primary btn-lg">Signup</button>
</form>
</div>
我的注册路线如下:
router.post("/register", function(req, res){
var newUser = new User({username: req.body.username, image: req.body.image});
User.register(newUser, req.body.password, function(err, user){
if(err){
res.redirect("/blogs");
console.log(err);
}
passport.authenticate("local")(req, res, function(){
res.redirect("/blogs");
});
});
})
如果密码字段不匹配,我需要抛出错误以防止用户注册。我认为最好编写一些中间件并将其插入寄存器路径,但我一直在玩代码,并且无法解决如何编写这个中间件。有人可以帮忙吗?
答案 0 :(得分:0)
如果条件为真,则创建一个“ err”数组并将错误推入其中。 包括以下验证。...
const err = [];
if( req.body.password1 !== req.body.password2 ){
err.push( {msg: "passwords do not match!! ") });
}
if( err.length > 0 ){
console.log(err);
res.render("/register");
}
因此,您的注册路线将如下所示。
router.post("/register", function(req, res){
var newUser = new User({username: req.body.username, image: req.body.image});
const err = [];
if( req.body.password1 !== req.body.password2 ){
errors.push( {msg: "passwords do not match!! ") });
}
if(err.length > 0){
console.log(err);
res.render("/register");
}
else{
User.register(newUser, req.body.password, function(err, user){
if(err){
res.redirect("/blogs");
console.log(err);
}
passport.authenticate("local")(req, res, function(){
res.redirect("/blogs");
});
});
}
});