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

Firebase实时数据库写入报错:app.database()不是函数求解决方案

解决Firebase实时数据库写入时“app.database() is not a function”错误

问题根源

你用的是Firebase v9模块化SDK,这个版本已经摒弃了v8那种app.database()的命名空间调用方式,必须通过显式导入数据库相关函数来操作,同时你还存在SDK版本不一致的问题(firebase-app是9.17.1,firebase-database是9.8.4),这也可能引发兼容问题。

修正步骤

  1. 统一Firebase SDK版本,确保所有导入的SDK版本一致
  2. 导入实时数据库所需的核心函数:getDatabase、ref、set
  3. 用模块化API重构数据写入逻辑

修正后的完整代码

<script type="module" src="https://www.gstatic.com/firebasejs/9.17.1/firebase-database.js"></script>
<script type="module">
  // Import the functions you need from the SDKs you need
  import { initializeApp } from "https://www.gstatic.com/firebasejs/9.17.1/firebase-app.js";
  import { getDatabase, ref, set } from "https://www.gstatic.com/firebasejs/9.17.1/firebase-database.js";

  // Your web app's Firebase configuration
  const firebaseConfig = {
    apiKey: "xxx",
    authDomain: "xxx",
    projectId: "xxx",
    storageBucket: "xxx",
    messagingSenderId: "xxx",
    appId: "xxx"
  };

  // Initialize Firebase
  const app = initializeApp(firebaseConfig);
  // 获取实时数据库实例
  const db = getDatabase(app);

  function writeUserData(userId, name, email) {
    // 创建指向指定路径的引用
    const userRef = ref(db, 'users/' + userId);
    // 写入数据
    set(userRef, {
      username: name,
      email: email
    });
  }
  
  writeUserData(1, "tester", "test@gmail.com");
</script>

关键说明

  • getDatabase(app):用来获取关联当前Firebase应用的实时数据库实例,替代v8的app.database()
  • ref(db, path):创建指向数据库指定路径的引用,对应v8的db.ref(path)
  • set(ref, data):将数据写入指定引用路径,是v9模块化版本的写入方法

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 11:33:01