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

无法从Firebase实时数据库获取数据的问题求助

问题:调用Firebase实时数据库db.ref()时报错TypeError: db.ref is not a function

我尝试从Firebase实时数据库获取数据,参考了Firebase官方文档教程,前端使用Svelte框架。

我的firebase.js配置代码:

// Import the functions you need from the SDKs you need
import { initializeApp } from 'firebase/app';
import { getDatabase } from 'firebase/database';
import { getAuth, GoogleAuthProvider } from 'firebase/auth';

const firebaseConfig = {
    apiKey: "AIzaSyCHL9UcT3TtvgQwt7N3DbLjRon9gKPFjA0",
    authDomain: "lyrics-and-quotes.firebaseapp.com",
    databaseURL: "https://lyrics-and-quotes-default-rtdb.firebaseio.com",
    projectId: "lyrics-and-quotes",
    storageBucket: "lyrics-and-quotes.appspot.com",
    messagingSenderId: "492758193692",
    appId: "1:492758193692:web:60ab73db53010e7fa7b1d9",
    measurementId: "G-T33YSTR82R",
};

// Initialize Firebase
initializeApp(firebaseConfig);

// Initialize Realtime Database and get a reference to the service
export const db = getDatabase(app);

// Initialize auth
export const auth = getAuth();

// Initialize Google auth provider
export const googleProvider = new GoogleAuthProvider();

前端组件Posts.svelte中的代码:

import { db } from '../database/firebase';
const postsRef = db.ref('posts');

遇到的错误:

Posts.svelte:5 Uncaught TypeError: db.ref is not a function

解决方案

1. 修复firebase.js中的未定义app变量

initializeApp(firebaseConfig)的结果未赋值给app变量,导致getDatabase(app)调用出错。修改代码如下:

// Initialize Firebase
const app = initializeApp(firebaseConfig); // 将初始化结果赋值给app

// Initialize Realtime Database and get a reference to the service
export const db = getDatabase(app);

2. 适配Firebase v9+模块化API

Firebase Web SDK v9及以上采用模块化设计,不再支持db.ref()这类命名空间调用方式,需单独导入ref函数创建数据库引用:

修改Posts.svelte中的代码:

import { db } from '../database/firebase';
import { ref } from 'firebase/database'; // 导入ref函数

const postsRef = ref(db, 'posts'); // 使用ref函数创建引用

如果需要读取数据,还需导入对应的数据读取函数,例如监听数据变化:

import { ref, onValue } from 'firebase/database';

// 监听posts节点的数据变化
onValue(postsRef, (snapshot) => {
  const data = snapshot.val();
  console.log(data);
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 00:10:47