You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

无法从Firebase Database获取数据?JS新手技术求助

解决Firebase用户信息无法获取并显示的问题

嘿,我看了你的代码,发现你踩了几个Firebase新手常见的小坑,咱们一步步把问题解决掉,让你能顺利展示用户的邮箱信息:

问题分析

  1. 数据库引用未定义:你在注册代码里用了database.ref('userProfile'),但根本没声明database变量,这会直接导致报错,没法读取数据库。
  2. 显示逻辑缺失:就算你读取了数据库快照,也只是遍历了数据,没有把获取到的email插入到页面元素里的代码。
  3. 页面跳转后脚本失效:登录成功后你跳转到了sample.html,但原来的登录页面脚本不会跟着跑到新页面,所以显示用户信息的逻辑应该放在sample.html里。
  4. API使用过时:新版Firebase的createUserWithEmailAndPassword返回的是UserCredential对象,你原来用newUser.uid是拿不到用户ID的,得改成newUserCredential.user.uid。

修改后的代码

1. 登录/注册页面的代码(比如login.html)

(function() { 
  // Initialize Firebase
  var config = {
    apiKey: "",
    authDomain: "",
    databaseURL: "",
    projectId: "",
    storageBucket: "",
    messagingSenderId: ""
  };
  firebase.initializeApp(config);
  // 新增:获取数据库引用,这一步很重要!
  const database = firebase.database();

  // 获取页面元素
  const txtEmail = document.getElementById('txtEmail');
  const txtPassword = document.getElementById('txtPassword');
  const btnLogin = document.getElementById('btnLogin');
  const btnSignup = document.getElementById('btnSignup');
  const btnLogout = document.getElementById('btnLogout');

  // 登录事件
  btnLogin.addEventListener('click', e => {
    const email = txtEmail.value;
    const pass = txtPassword.value;
    const auth = firebase.auth();
    const promise = auth.signInWithEmailAndPassword(email,pass);
    promise.catch(e => console.log(e.message));
  });

  // 注册事件
  btnSignup.addEventListener('click', e => {
    const email = txtEmail.value;
    const pass = txtPassword.value;
    const auth = firebase.auth();
    
    auth.createUserWithEmailAndPassword(email,pass)
      .then(newUserCredential => {
        // 新版API要通过.user获取用户对象
        const user = newUserCredential.user;
        // 把用户邮箱存入数据库
        return database.ref('userProfile').child(user.uid).set({email: email });
      })
      .then(() => {
        console.log("用户信息已成功保存到数据库");
        // 注册成功后可以提示用户,或者自动登录
      })
      .catch(e => console.log(e.message));
  });

  // 登出事件
  btnLogout.addEventListener('click', e => {
    firebase.auth().signOut();
  });

  // 监听用户登录状态变化
  firebase.auth().onAuthStateChanged(firebaseUser => {
    if (firebaseUser) {
      btnLogout.classList.remove('hide');
      // 登录成功跳转到用户信息页面
      window.location = 'sample.html';
    } else {
      console.log('用户未登录');
      btnLogout.classList.add('hide');
    }
  });
}());

2. 用户信息展示页面(sample.html)

先在HTML里加一个用来显示邮箱的元素,然后写脚本读取并展示数据:

<!DOCTYPE html>
<html>
<head>
  <title>用户信息</title>
</head>
<body>
  <!-- 用来显示用户邮箱的元素 -->
  <h3>当前登录用户邮箱:<span id="userEmail"></span></h3>

  <!-- 引入Firebase SDK -->
  <script src="https://www.gstatic.com/firebasejs/8.10.0/firebase-app.js"></script>
  <script src="https://www.gstatic.com/firebasejs/8.10.0/firebase-auth.js"></script>
  <script src="https://www.gstatic.com/firebasejs/8.10.0/firebase-database.js"></script>
  
  <script>
    // 初始化Firebase配置(和登录页面一致)
    var config = {
      apiKey: "",
      authDomain: "",
      databaseURL: "",
      projectId: "",
      storageBucket: "",
      messagingSenderId: ""
    };
    firebase.initializeApp(config);
    const database = firebase.database();
    // 获取显示邮箱的页面元素
    const userEmailElement = document.getElementById('userEmail');

    // 监听用户登录状态,获取并显示用户信息
    firebase.auth().onAuthStateChanged(firebaseUser => {
      if (firebaseUser) {
        // 根据当前用户的UID读取数据库中的用户信息
        database.ref('userProfile').child(firebaseUser.uid).on('value', snapshot => {
          const userData = snapshot.val();
          if (userData && userData.email) {
            // 把邮箱显示到页面上
            userEmailElement.textContent = userData.email;
          }
        });
      } else {
        // 如果用户未登录,跳回登录页面
        window.location = 'login.html';
      }
    });
  </script>
</body>
</html>

额外提示

  • 不用手动存cookie传递邮箱,Firebase会自动在浏览器中维护用户的登录状态,onAuthStateChanged在任何页面都能获取到当前登录的用户。
  • 记得给Firebase数据库设置合适的安全规则,比如只允许登录用户读取自己的信息,避免数据泄露。

内容的提问来源于stack exchange,提问作者John

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 06:40:01