JS Firebase 数据库错误 db.ref 不是函数

Con*_*nta 2 javascript firebase firebase-realtime-database

您好,我正在尝试在我的网站中实现 firebase 实时数据库 API,我正在遵循此文档: https: //firebase.google.com/docs/database/admin/save-data#node.js但我收到此错误:

在此输入图像描述

这是我的代码:

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

    // TODO: Add SDKs for Firebase products that you want to use
    // https://firebase.google.com/docs/web/setup#available-libraries

    // Your web app's Firebase configuration
    // For Firebase JS SDK v7.20.0 and later, measurementId is optional
    const firebaseConfig = {
      apiKey: "xxxxxxxxxxxxxxxxxxxxx",
      authDomain: "xx.x.xxx",
      databaseURL: "xxxxxxxxxxxxxxxx",
      projectId: "xxxxx",
      storageBucket: "xxxxxxxxx",
      messagingSenderId: "xxxx",
      appId: "xxxxx",
      measurementId: "xxxxxxx"
    };

    const fireapp = initializeApp(firebaseConfig);
    const db = getDatabase(fireapp);
    const ref = db.ref('server/saving-data/fireblog');
  </script>
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?难道是我使用的版本不对?

Fra*_*len 5

您将 API 的新模块化/v9 语法与旧的命名空间语法混合在一起,这是行不通的。

在 v9 中,最后一行相当于:

将“ ref”添加到imports from firebase/database

import { getDatabase, ref } 
  from "<wherever you are getting firebase/database from>";
Run Code Online (Sandbox Code Playgroud)

并替换你的最后一行:

const dbref = ref(db, 'server/saving-data/fireblog');
Run Code Online (Sandbox Code Playgroud)

由于您似乎正在使用过时的代码,因此我建议您将文档放在手边(例如,有关获取参考的本节)以比较 v8 和 v9 代码示例,以及阅读升级指南