如何在javascript和Firebase中使用"createUserWithEmailAndPassword(email, password)"时获取用户ID



我正在使用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>

客户端 SDK 的createUserWithEmailAndPassword()函数在成功创建时不会返回用户对象,请查看此处的这些文档,其中解释了">如果创建了新帐户,则用户将自动登录"并且没有提到返回的用户对象,并且他们的示例都没有这样的事情。

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

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

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

createUserWithEmailAndPassword 返回一个包含 UserCredential 的承诺 - 而不是用户。

试试这个片段:

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

相关内容

最新更新