2016-10-16 48 views
1

问题:如何使用Node.js在Firebase中注册用户?

0)用户被在火力地堡的身份验证系统(I看到它在验证标签)创建的,

1)但是,没有改变对数据库进行。

2)页面似乎被无限加载。

3)仅 “开始1 ...” 登录到控制台。


CODE:

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

    // Validation 
    req.checkBody('username', 'Username is required').notEmpty(); 
    req.checkBody('email', 'Email is required').notEmpty(); 
    req.checkBody('email', 'Email is not valid').isEmail(); 
    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('users/register', { 
      errors: errors 
     }); 
    } else { 
     console.log("Started 1..."); 
     firebase.auth().createUserWithEmailAndPassword(email, password).catch(function(error, userData) { 
      console.log("Started 2..."); 
      if(error){ 
       var errorCode = error.code; 
       var errorMessage = error.message; 
       req.flash('error_msg', 'Registration Failed. Make sure all fields are properly filled.' + error.message); 
       res.redirect('/users/register'); 
       console.log("Error creating user: ", error); 
      } else { 
       console.log("Successfully created"); 
       console.log("Successfully created user with uid:", userData.uid); 
       var user = { 
        uid: userData.uid, 
        email: email, 
        username: username 
       } 

       var userRef = firebase.database().ref('users/'); 
       userRef.push().set(user); 

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

     }); 
    } 
}); 

编辑1:

这是什么似乎是发生的事情:在身份验证系统中创建

用户。页面加载大约5分钟(非常长!),然后告诉我注册失败,因为电子邮件地址已被使用(不是)。

这似乎是创建的用户,而是因为,如果它没有被创建,创建后的用户,因此创建类型的错误代码循环回注册失败:这个电子邮件地址已经在我们的数据库。

但为什么会发生这种情况?

回答

4

不知道这一切,但这里是我想发生:创建

用户,但你没有正确地处理它。没有处理成功案例(履行承诺),只有被拒绝的案例。另外,当您在发生错误时尝试写入数据库时​​,这意味着用户未通过身份验证,这意味着如果您尚未更改Firebase安全规则,则无法写入。 (默认火力安全规则可以防止非认证用户读取/写入到数据库)

这一行:

firebase.auth().createUserWithEmailAndPassword(email,password) .catch(function(error, userData) { ...

应该改成这样:

firebase.auth().createUserWithEmailAndPassword(email, password) .then(userData => { // success - do stuff with userData }) .catch(error => { // do stuff with error })

请注意,发生错误时,您将无法访问userData,只是出现错误。

希望这会有所帮助!

+0

谢谢!不知何故,我知道我的语法错了。目前正在学习Node.js. – Coder1000