Node.js检查用户是否已存在

时间:2018-04-03 18:07:09

标签: javascript html node.js

大家好我试图检查用户是否已经存在于数据库中,如果已经存在同名的用户,我已设法停止创建用户,但是我似乎没有显示错误消息。我不太清楚为什么我的错误没有得到正确处理。这是我的代码:

 // Register User
    router.post('/register', function(req, res){
        var name = req.body.name;
        var email = req.body.email;
        var username = req.body.username;
        var password = req.body.password;
        var password2 = req.body.password2;

    //Validation
    req.checkBody('name', 'Name is required').notEmpty();
    req.checkBody('email', 'Email is required').notEmpty();
    req.checkBody('email', 'Email is not valid').isEmail();
    req.checkBody('username', 'Username is required').notEmpty();
    req.checkBody('password', 'Password is required').notEmpty();
    req.checkBody('password2', 'Passwords do not match').equals(req.body.password);

    var errors = req.validationErrors();

    if(errors){
        res.render('register',{
            errors:errors
        });
    }else{var newUser = new User({
        name: name,
        email:email,
        username: username,
        password: password
    });

    User.getUserByUsername(username, function(err, user){
        if(err) throw err;
        if(user){
            return new Error('User already exists!');
        }else{
            User.createUser(newUser, function(err, user){
                if(err) throw err;
                console.log(user);
            });
        }
    });


    req.flash('success_msg', 'You are registered and can now login');

    res.redirect('/users/login');
    }
});

4 个答案:

答案 0 :(得分:1)

这将完全按照您的意愿运行。我在尝试使其正常工作时遇到了同样的问题,我向您保证。干杯!

User.getUserByUsername(username, function(err, user){ //must check if user exists
  if(err) throw err;
  if(user){
    console.log('existing...'); //may be deleted
    req.flash('error_msg', 'This username already exists');
    res.redirect('/users/register');
  } else {
    User.createUser(newUser, function(err, user){
    if(err) throw err;
    console.log(user);//may be deleted
    });

  req.flash('success_msg', 'You registered successfuly and you can now login');
  res.redirect('/users/login');
  }
})

答案 1 :(得分:0)

我看错了两件事:

  • 在将控件传递给异步回调后,您正在执行同步操作

  • 您没有对异步回调中的错误做任何有用的事情

此处异步回调是您传递给User.getUserByUsername

的函数
router.post('/register', function(req, res) {
  ...
  User.getUserByUsername(username, function(err, user) {
    // Any errors get thrown here need to be dealt with here
    // Also you can't simply "throw" or "return" errors from this,
    // You need to use Express's "next" method to handle these errors
  })

  // And since you've gone asynchronous above (User.getUserByUsername) 
  // you can't do the following here:
  req.flash('success_msg', 'You are registered and can now login')
  res.redirect('/users/login')
  // otherwise these will ALWAYS get executed, 
  // regardless of what the result of `User.getUserByUsername` may be
})

你需要做这样的事情:

router.post('/register', function(req, res, next) { // use `next` to handle errors
  ...
  User.getUserByUsername(username, function(err, user) {
    if (err) {
      next(err)
    } else if (user) {
      next(new Error('User already exists!'))
    } else {
      req.flash('success_msg', 'You are registered and can now login')
      res.redirect('/users/login')
    }
  })
})

PS:您还没有保存newUser(至少没有保存在您发布的代码中)

答案 2 :(得分:0)

var candidateName = username;
var queryforUsername = {};
queryforUsername['username'] = candidateName;
User.find(queryforUsername, function(err, item){
    if(err) throw (err);
    if(item.length > 0){
        req.flash('error_msg', 'User with username '+username+' already exists!');
        res.redirect('register');
    }else if(item.length == 0){
        User.createUser(newUser, function(err, user){
            if(err) throw err;
            console.log(user);
            req.flash('success_msg', 'You are registered and can now login');
            res.redirect('/users/login');
        });
    }
});

答案 3 :(得分:0)

如果您只想检查具有给定用户名的用户是否存在,那么我已经使用了这个简单的技巧。

我正在做的是注册时,如果发生某些错误,那么我正在检查此错误是否为UserExistError(与mongodb有关,您可以在终端中看到它)

如果err等于UserExistError,则我将呈现一个警报,该警报位于单独的文件中。

register(new User({username:req.body.username}),req.body.password,function(err,user){
    if(err)
    {   var chk=1;
        console.log(err);
        if(err=='UserExistsError');
        console.log("error is here");
        return res.render("register",{chk:chk});

    }

    passport.authenticate("local")(req,res,function(){
        res.redirect("/dashboard");
    })    

});
相关问题