Firebase获取当前用户用户名返回undefined,仅邮箱可正常获取如何解决?
问题根因
- 存储逻辑位置错误:你将用户自定义数据写入数据库的逻辑放在了
createUserWithEmailAndPassword的catch回调中,只有注册失败时才会触发这段写入逻辑,注册成功的用户根本不会生成对应的自定义数据记录 - 存储结构不合理:使用
push()方法写入数据会生成随机唯一键作为记录ID,后续无法通过用户UID快速匹配到对应用户数据 - 读取逻辑错误:
onAuthStateChanged返回的user是Firebase Auth体系的原生用户对象,仅包含邮箱、UID等Auth内置字段,你存在实时数据库的自定义字段(用户名、性别等)不会同步到这个对象中,直接访问user.Nume必然返回undefined - 安全风险:不要在数据库中明文存储用户密码,Firebase Auth已经完成了密码的加密存储,额外明文存储会产生严重的用户数据泄露风险
修正后的注册存储代码
document.getElementById('intrebari').addEventListener("submit", (e) => { e.preventDefault(); const email = document.getElementById('Email'); const nume = document.getElementById('NumeUtilizator'); const parola = document.getElementById('ParolaInregistrare'); const conf = document.getElementById('ConfirmareParola'); const gen = document.getElementById('gen'); const platforma = document.getElementById('platforma'); const on_off = document.getElementById('on_off'); const timp = document.getElementById('timp'); firebase.auth().createUserWithEmailAndPassword(email.value, parola.value) // 注册成功走then回调,写入自定义数据 .then((userCredential) => { const user = userCredential.user; // 用用户UID作为记录键,方便后续查询 return firebase.database().ref('utilizatori/' + user.uid).set({ Nume: nume.value, Email: email.value, Gen: gen.value, Platforma: platforma.value, Online_Offline: on_off.value, Timp: timp.value, userID: user.uid, email: user.email }) }) .then(() => { location.reload(); }) // 注册失败才走catch做错误处理 .catch(function (error) { console.log(error.message); if (error.message === "The email address is badly formatted.") { $("#eroare_inregistrare").show().text("Introdu un email valid"); } if (error.message === "The email address is already in use by another account.") { $("#eroare_inregistrare").show().text("Acest email este deja folosit.") } }) })
修正后的用户名字段读取代码
function get() { firebase.auth().onAuthStateChanged(function (user) { if (user) { // 从实时数据库查询当前UID对应的用户自定义数据 firebase.database().ref('utilizatori/' + user.uid).once('value') .then((snapshot) => { if (snapshot.exists()) { const userData = snapshot.val(); console.log(userData.Nume); } else { console.log("未找到对应用户数据"); } }) } else { console.log("no user is sign in"); } }); }
内容的提问来源于stack exchange,提问作者alexandru cretu
相关产品推荐
相关产品推荐

