首页 > 解决方案 > 在javascript和firebase中使用“createUserWithEmailAndPassword(email,password)”时如何获取用户ID

问题描述

我正在使用 firebase 和 javascript 创建新的网络应用程序。更准确地说,我用\firebase.auth().createUserWithEmailAndPassword(email, password)It is working 注册了新用户,但是当我使用这个关键字时,我想获取一个新用户的 UID 并将其初始化为一个新变量。在此之后,我想使用这个键 UID(即姓名、年龄等)在数据库中添加新用户。我尝试console.log(user.uid)在浏览器中使用它来显示它,但它显示为未定义。请帮我。

Code.html

<input type="email" id="txtEmail" placeholder="username">
<input type="email" id="txtPass" placeholder="password">

<button id="btnSignUp" type="submit" onclick="Press()"> SignUp</button>

<script src="https://www.gstatic.com/firebasejs/5.2.0/firebase.js"></script>
<script >
        // Initialize Firebase
  var config = {
    apiKey: "api key",
    authDomain: "bigpro-c6a4c.firebaseapp.com",
    databaseURL: "https://bigpro-c6a4c.firebaseio.com",
    projectId: "bigpro-c6a4c",
    storageBucket: "",
    messagingSenderId: "id"
  };
  firebase.initializeApp(config);
</script>

<script>
     function Press(){

  var txtEmail = document.getElementById('txtEmail');
  var txtPass = document.getElementById('txtPass');
  var txtEmail = document.getElementById('txtEmail');
  var txtPass = document.getElementById('txtPass');

    var email = txtEmail.value;
    var password=txtPass.value;
  firebase.auth().createUserWithEmailAndPassword(email, password)
        .then(function(user){
          // console.log('uid',user.uid);
          console.log(user.uid);
        }).catch(function(error) {

        });

}

</script>

标签: javascriptfirebasefirebase-authentication

解决方案


客户端 SDK 的createUserWithEmailAndPassword()函数在成功创建时不会返回用户对象,请查看这些文档,其中解释了“如果创建了新帐户,则用户自动登录”并且没有提及返回的用户对象,并且他们的例子都没有这样的东西。

您正在考虑(或查看Admin SDK - 它确实返回用户对象

相反,对于客户端,您需要访问新创建的(因此当前登录的)用户...。

firebase.auth().createUserWithEmailAndPassword(email, password)
    .then(function () {
        console.log(firebase.auth().currentUser.uid)
    }).catch(function (error) {
        console.log(error)
    });

推荐阅读