javascript - 在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>
解决方案
客户端 SDK 的createUserWithEmailAndPassword()
函数在成功创建时不会返回用户对象,请查看这些文档,其中解释了“如果创建了新帐户,则用户自动登录”并且没有提及返回的用户对象,并且他们的例子都没有这样的东西。
您正在考虑(或查看)Admin SDK - 它确实返回用户对象。
相反,对于客户端,您需要访问新创建的(因此当前登录的)用户...。
firebase.auth().createUserWithEmailAndPassword(email, password)
.then(function () {
console.log(firebase.auth().currentUser.uid)
}).catch(function (error) {
console.log(error)
});
推荐阅读
- pine-script - 交易视图的 Pinscript
- python - 如何在tensorflow的vectorized_map中使用TopK算子
- java - Jess - 有没有一种有效的方法来检查一个事实是否仍在工作记忆中?
- javascript - 计算threecsg网格的UV坐标
- python - ValueError: Expected 2D array, got 1D array instead: 对于矩阵?
- forms - SwiftUI 表单中的动态行高
- python - 只下载了 5 中的一个图像,它敲出一个错误
- airflow - 气流未从 DAG 获取“start_date”
- c# - 是否可以通过SqlDataReader 获取SQL 列的长度?
- django - Django 频道实时聊天保存发送的消息