繁体   English   中英

在javascript和firebase中使用“ createUserWithEmailAndPassword(电子邮件,密码)”时如何获取用户ID

[英]How to take user Id when using “createUserWithEmailAndPassword(email, password)” in javascript and firebase

我正在使用Firebase和JavaScript创建新的Web应用程序。 更精确地说,我使用\\firebase.auth().createUserWithEmailAndPassword(email, password)注册了新用户,它可以正常工作,但是当我使用此关键字时,我想获取新用户的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>

createUserWithEmailAndPassword返回包含UserCredential而非用户Promise

试试以下代码片段:

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

    });

客户端SDK的createUserWithEmailAndPassword()函数创建成功后不会返回用户对象,请在此处查看这些文档,文档说明“ 如果创建了新帐户,则用户将自动登录 ”,并且未提及该用户对象。返回,他们的例子都没有这样的事情。

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM