Firebase报错Uncaught TypeError: db.ref is not a function求助
解决Firebase v9中
Uncaught TypeError: db.ref is not a function错误 你遇到的问题是因为Firebase v9采用了模块化API,和旧版v8的命名空间写法完全不同,db.ref()这种链式调用在v9里已经被废弃,必须使用导入的独立工具函数来创建数据库引用。
具体修正步骤:
若需要分步构建路径,先确保导入
child函数(已有ref的话,按需添加):import { getDatabase, ref, set, get, child } from "https://www.gstatic.com/firebasejs/9.14.0/firebase-database.js";将创建引用的代码替换为模块化写法,两种可选方式:
- 方式一:直接在
ref函数中指定完整路径(更简洁)const coleccionProductos = ref(db, "productos"); - 方式二:用
child函数分步拼接路径(适合动态生成路径的场景)const rootRef = ref(db); const coleccionProductos = child(rootRef, "productos");
- 方式一:直接在
修正后的完整代码示例:
// Import the functions you need from the SDKs you need import { initializeApp } from "https://www.gstatic.com/firebasejs/9.14.0/firebase-app.js"; import { getDatabase, ref, set, get } from "https://www.gstatic.com/firebasejs/9.14.0/firebase-database.js"; // Your web app's Firebase configuration const firebaseConfig = { apiKey: "AIzaSyAalz5fFuOOG6_EZVFIO-hJRA2Sw1Yyg2A", authDomain: "lost-and-found-system-67568.firebaseapp.com", databaseURL: "https://lost-and-found-system-67568-default-rtdb.firebaseio.com", projectId: "lost-and-found-system-67568", storageBucket: "lost-and-found-system-67568.appspot.com", messagingSenderId: "32608786023", appId: "1:32608786023:web:6aea01187ecb53ce6a66c2" }; // Initialize Firebase const app = initializeApp(firebaseConfig); const db = getDatabase(app); // 修正后的引用创建代码 const coleccionProductos = ref(db, "productos"); const bodyProductos = $("#bodyProductos").val(); // console.log(bodyProductos);
额外提醒:尽量给变量加上const或let声明,避免意外的全局变量污染。
内容的提问来源于stack exchange,提问作者Angular_JS_Hater
相关产品推荐
相关产品推荐

