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

Cod*_*000 2 javascript node.js express firebase firebase-realtime-database

问题:

0)用户是在 Firebase 的身份验证系统中创建的(我在“身份验证”选项卡中看到它),

1)但没有对数据库进行任何更改。

2)页面似乎无限加载。

3) 仅“Started 1...”记录到控制台。


代码:

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');
            }

        });
    }
});
Run Code Online (Sandbox Code Playgroud)

编辑1:

这似乎正在发生:

用户是在 auth 系统中创建的。页面加载大约 5 分钟(非常长!),然后告诉我注册失败,因为电子邮件地址已在使用中(实际上并未使用)。

似乎用户已创建,但注册失败,因为代码在创建用户后循环返回,就好像尚未创建一样,因此创建了类型错误:此电子邮件地址已在我们的数据库中。

但为什么会出现这种情况呢?

Uzi*_*Uzi 5

不确定这就是全部,但我认为会发生以下情况:

用户已创建,但您没有正确处理它。没有成功案例(履行承诺)的处理,只有被拒绝的案例。另外,当您尝试写入数据库时​​发生错误,这意味着用户未经过身份验证,这意味着如果您没有更改 firebase 安全规则,您将无法写入。(默认的 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,而只能访问错误。

希望这可以帮助!