【发布时间】:2021-12-06 02:04:03
【问题描述】:
如果这不是一个好问题,我深表歉意(我对 Firebase 和 JavaScript 编程相当陌生)。
我一直在尝试启动并运行一个相对简单的程序。具体来说,当我运行我的代码时,我希望出现一个“开始”按钮。一旦用户点击此按钮,它会将玩家数量加一,并相应地更新我的 Firebase 实时数据库中的 playerCount。
我注意到当我运行这个程序时,我得到一个错误:“Uncaught TypeError: database.ref is not a function”
这是我的 index.html 代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script defer type="module" src="https://www.gstatic.com/firebasejs/9.1.3/firebase-app.js"></script>
<script defer type="module" src="https://www.gstatic.com/firebasejs/9.1.3/firebase-firestore.js"></script>
<script defer type="module" src="//cdn.jsdelivr.net/npm/phaser@3.11.0/dist/phaser.js"></script>
<script defer type="module" src="game.js"></script>
<style type="text/css">
body {
margin: 0;
}
</style>
</head>
<body>
</body>
</html>
这是我的 game.js 代码:
import { initializeApp } from "https://www.gstatic.com/firebasejs/9.1.3/firebase-app.js";
import { getDatabase } from 'https://www.gstatic.com/firebasejs/9.1.3/firebase-database.js';
// Your web app's Firebase configuration
// For Firebase JS SDK v7.20.0 and later, measurementId is optional
const firebaseConfig = {
apiKey: "apiKey information",
authDomain: "authDomain information",
databaseURL: "databaseURL information",
projectId: "projectId information",
storageBucket: "storageBucket information",
messagingSenderId: "messagingSenderId information",
appId: "appId information",
measurementId: "measurementId information"
};
const app = initializeApp(firebaseConfig);
// Store Firestore database in db
const database = getDatabase(app);
var player_num = 0;
// Display Start Button and increment player count
let button = document.createElement('button');
button.innerHTML = "Start";
button.onclick = function () {
player_num++;
database.ref('/').update({
playerCount: player_num
});
button.style.display = "none";
};
document.body.appendChild(button);
我怀疑我可能没有正确设置浏览器模块,但我不完全确定。任何帮助将不胜感激!
【问题讨论】:
-
如果
apiKey、authDomain和databaseUrl是真实的,我建议您从您的问题中删除它们。 -
database.ref('/')这似乎不对。通常,您会查找名称类似于database.ref('game')的根节点。能发一下数据结构吗? -
嗨@Papa,非常感谢您让我知道我的
apiKey、authDomain和databaseUrl(现在已修复)。你是对的,database.ref('/')不正确。我检查了 Firebase 文档,我的代码现在可以使用:set(ref(db, 'game/'), { playerCount: player_num });。我还从 firebase-database 导入了set。以后我会关注官方documentation(而不是过时的YouTube教程)。
标签: javascript firebase firebase-realtime-database typeerror