Firebase前端无法展示用户名、手机号及机构信息求助
解决方案:Firebase实时数据库用户信息无法在Profile页面展示
问题根源
注册流程已将用户名、手机号、机构信息存入Firebase Realtime Database的users/{uid}节点,但当前profile页面仅从Firebase Auth模块获取用户邮箱,未对接数据库读取额外信息;同时DOM元素ID配置错误(如用户名展示节点使用了email ID),导致完整用户信息无法正常展示。
步骤1:修正Profile页面DOM结构
在profile.html的profile-section中添加对应信息的展示节点,为每个字段设置唯一ID:
<div class="profile-section"> <h2>User Info:</h2> <p>Username: <span id="username"></span></p> <p>Email: <span id="email"></span></p> <p>Phone: <span id="phone"></span></p> <p>Institution: <span id="institution"></span></p> </div>
步骤2:完善Firebase数据库读取逻辑
在profile.html的脚本模块中,新增数据库相关方法导入,并在用户登录状态变化时,通过用户UID从数据库读取对应详情:
修改后的完整脚本代码:
<script type="module"> import { initializeApp } from "https://www.gstatic.com/firebasejs/9.18.0/firebase-app.js"; import { getAuth, onAuthStateChanged } from "https://www.gstatic.com/firebasejs/9.18.0/firebase-auth.js"; // 新增导入数据库操作方法 import { getDatabase, ref, get } from "https://www.gstatic.com/firebasejs/9.18.0/firebase-database.js"; const firebaseConfig = { apiKey: "AIzaSyBiydb9tqJp526GBYwTqv3S7P_ErmOntLg", authDomain: "mom-login-a6e00.firebaseapp.com", databaseURL: "https://mom-login-a6e00-default-rtdb.firebaseio.com", projectId: "mom-login-a6e00", storageBucket: "mom-login-a6e00.appspot.com", messagingSenderId: "14987956774", appId: "1:14987956774:web:f55080976493fa99a20ce7" }; const app = initializeApp(firebaseConfig); const auth = getAuth(app); // 初始化数据库实例 const database = getDatabase(app); onAuthStateChanged(auth, async (user) => { if (user) { // 展示Auth模块返回的邮箱 document.getElementById('email').textContent = user.email; try { // 通过用户UID定位数据库中的用户节点 const userRef = ref(database, `users/${user.uid}`); const snapshot = await get(userRef); if (snapshot.exists()) { const userData = snapshot.val(); // 将数据库中的用户信息填充到DOM节点 document.getElementById('username').textContent = userData.username; document.getElementById('phone').textContent = userData.phone; document.getElementById('institution').textContent = userData.institution; } else { console.log("数据库中未找到该用户的详细信息"); } } catch (error) { console.error("读取用户数据失败:", error); } } else { console.log("当前无登录用户"); } }); </script>
关键补充配置
确保Firebase Realtime Database的安全规则允许已登录用户读取自身数据,建议将规则修改为:
{ "rules": { "users": { "$uid": { ".read": "$uid === auth.uid", ".write": "$uid === auth.uid" } } } }
内容的提问来源于stack exchange,提问作者Priti
相关产品推荐
相关产品推荐

