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

Web端连接Firebase Realtime Database时报错firebase is not defined

报错原因

你使用的是 Firebase 9.x 模块化 SDK,该版本已经移除了全局的 firebase 命名空间对象,你代码里写的 firebase.database() 是 Firebase 8.x 及更早版本的用法,因此会抛出 firebase is not defined 的引用错误。

修复方案
  • 先引入 Realtime Database 对应的模块化 API
  • 替换原有命名空间风格的数据库操作逻辑,改用模块化 API 实现数据写入
修改后的完整代码
<script type="module">
      import { initializeApp } from "https://www.gstatic.com/firebasejs/9.5.0/firebase-app.js";
      import { getAnalytics } from "https://www.gstatic.com/firebasejs/9.5.0/firebase-analytics.js";
      // 新增导入Realtime Database相关方法
      import { getDatabase, ref, push, set } from "https://www.gstatic.com/firebasejs/9.5.0/firebase-database.js";

      const firebaseConfig = {
        apiKey: "<api key>",
        authDomain: "<domain>",
        databaseURL: "<db url>",
        projectId: "<project id>",
        storageBucket: "<bucket>",
        messagingSenderId: "<id>",
        appId: "<app id>",
        measurementId: "<id>"
      };

      const app = initializeApp(firebaseConfig);
      const analytics = getAnalytics(app);
      // 初始化数据库实例
      const db = getDatabase(app);
      // 构建节点引用、生成新节点、写入数据
      const postListRef = ref(db, 'posts');
      const newPostRef = push(postListRef);
      set(newPostRef, {
        "post1": "testing"
      });
</script>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 10:54:04