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

如何在HTML中通过Firebase实现登录后显示用户名并解决导入错误

问题修复与实现方案

一、解决SyntaxError错误

这个错误是因为浏览器默认不识别ES模块的import语法,必须在引入JS文件的<script>标签中添加type="module"属性,明确告诉浏览器这是一个ES模块文件。

修正HTML中的Script标签

把原来的引入代码:

<script src="你的脚本文件名.js"></script>

修改为:

<script type="module" src="你的脚本文件名.js"></script>

二、优化Firebase代码,正确读取用户名

除了模块问题,还可以优化代码逻辑,提升可靠性:

修正后的JavaScript代码

// Import the functions you need from the SDKs you need
import { initializeApp } from "https://www.gstatic.com/firebasejs/9.20.0/firebase-app.js";
import { getAnalytics } from "https://www.gstatic.com/firebasejs/9.20.0/firebase-analytics.js";
import { getAuth } from "https://www.gstatic.com/firebasejs/9.20.0/firebase-auth.js";
import { getDatabase, onValue, ref } from "https://www.gstatic.com/firebasejs/9.20.0/firebase-database.js";

// Your web app's Firebase configuration
const firebaseConfig = {
    // 填入你的Firebase配置信息
};

// Initialize Firebase
const app = initializeApp(firebaseConfig);
const database = getDatabase(app); // 传入app实例,避免潜在初始化问题
const analytics = getAnalytics(app);
const auth = getAuth(app);

auth.onAuthStateChanged((user) => {
    if (user) {
        // 直接使用回调中的user对象,比auth.currentUser更可靠
        const userID = user.uid;
        const athleteRef = ref(database, `Athletes/${userID}/firstname`);
        
        onValue(athleteRef, (snapshot) => {
            if (snapshot.exists()) {
                const nombre = snapshot.val();
                document.getElementById('nombre-atleta').textContent = nombre;
            } else {
                // 处理用户数据不存在的情况
                document.getElementById('nombre-atleta').textContent = "运动员";
            }
        }, (error) => {
            // 监听数据库读取错误
            console.error("读取用户数据失败:", error);
        });
    } else {
        console.log("用户未登录,跳转至登录页");
        window.location.href = "loginTrainMate.html";
    }
});

对应的HTML欢迎消息部分

确保页面中有匹配的DOM元素:

<h1>欢迎来到训练门户,<span id="nombre-atleta"></span>!</h1>

三、额外注意事项

  • 配置Firebase数据库规则,允许已登录用户读取自己的数据,示例规则:
    {
      "rules": {
        "Athletes": {
          "$uid": {
            ".read": "$uid === auth.uid",
            ".write": "$uid === auth.uid"
          }
        }
      }
    }
    
  • 若不需要Analytics功能,可移除getAnalytics相关代码,减少资源加载量。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 06:12:55