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

Vue应用无法从Firebase获取数据(permission-denied错误)的解决方法

问题描述

我创建了一个带数据库的Firebase应用,将其和类待办事项的Vue应用对接。尝试从Firebase数据库拉取数据生成应用组件时出了问题——Vue应用拿不到数据,组件无法创建。

报错信息

@firebase/firestore: Firestore (9.10.0): Uncaught Error in snapshot listener: {"code":"permission-denied","name":"FirebaseError"

Firebase初始化代码

import { initializeApp } from "firebase/app";
import { getDatabase } from "firebase/database";
import { getFirestore } from "@firebase/firestore";

const firebaseConfig = {
apiKey: "AIzaSyBZlP_E74i40ZLopttFlUbg3j36wirKf9A",
authDomain: "quotes-app-8788c.firebaseapp.com",
projectId: "quotes-app-8788c",
storageBucket: "quotes-app-8788c.appspot.com",
messagingSenderId: "934346412075",
appId: "1:934346412075:web:5da2928fecb05c834f5a6e"
};

const app = initializeApp(firebaseConfig);
 const db = getFirestore(app);


export {
  db
}

数据获取代码

onSnapshot(collection(db, 'quotes'), (QuerySnapshot) => {
         const fbquotes = [];
         QuerySnapshot.forEach((doc) => {
          const quote = {
            id: doc.data().id,
            quoteText: doc.data().quoteText,
            quoteAuthor: doc.data().quoteAuthor,
            quoteGenre: doc.data().quoteGenre,
            timeCreating: doc.data().timeCreating,
            timeEditing: doc.data().timeEditing
          }
          this.fbquotes.push(quote)
         })
         this.quotes = fbquotes
         console.log(this.quotes);
    })
    console.log(this.quotes);
},
解决方案

这个permission-denied错误是Firestore的安全规则阻止了你的读取请求——默认情况下Firebase会关闭所有数据库访问权限。

临时调试方案(仅开发环境使用)

登录Firebase控制台,找到你的项目,进入Firestore数据库 → 规则标签,把规则修改为:

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
      allow read, write: if true;
    }
  }
}

点击发布。这样就能临时允许所有读写操作,验证是否是权限问题导致组件无法加载。

生产环境安全规则

开发完成后必须改回严格规则,比如只允许已认证用户访问:

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /quotes/{quote} {
      allow read, write: if request.auth != null;
    }
  }
}

额外检查点

  • 确认你的Firestore数据库已创建(注意你代码里同时引入了Realtime Database,但实际用的是Firestore,别搞混)
  • 检查quotes集合是否存在,文档结构和你代码中读取的字段完全匹配
  • 确认Vue代码里的this.fbquotes和this.quotes已正确声明为响应式数据

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 23:25:24