【问题标题】:Connecting Firebase DB to Next.js app error将 Firebase DB 连接到 Next.js 应用程序错误
【发布时间】:2020-12-30 20:27:47
【问题描述】:

我正在尝试连接我的 NextJS 应用以从我的 Firebase 数据库中获取数据。我的实现基于此示例:https://github.com/firebase/quickstart-nodejs/tree/master/database

这是我目前所拥有的:

在 lib/firebase.js 中

import firebase from "firebase-admin";
const serviceAccount = require("../serviceAccount.json");

firebase.initializeApp(
  {
    credential: firebase.credential.cert(serviceAccount),
    databaseURL: "https://myDB.firebaseio.com",
  },
  "DB"
);

export default firebase;

然后在 pages/index.js 中

import firebase from "../lib/firebase";

export async function getStaticProps(context) {
  var test = firebase.database().ref("artsci");
  test.on("value", function (snapshot) {
    return {
      props: { test }, // will be passed to the page component as props
    };
  });
}

但是,每当我运行 yarn dev 时,我都会收到此错误:

错误:名为“DB”的 Firebase 应用已存在。这意味着您使用与第二个参数相同的应用程序名称多次调用了 initializeApp()。确保每次调用 initializeApp() 时都提供一个唯一的名称。

另外,如果我将此行添加到我的 firebase.js

if (!firebase.apps.length) {
  firebase.initializeApp(
    {
      credential: firebase.credential.cert(serviceAccount),
      databaseURL: "https://myDB.firebaseio.com",
    },
    "DB"
  );
}

然后我得到这个错误:

错误:默认 Firebase 应用不存在。确保在使用任何 Firebase 服务之前调用 initializeApp()。

任何提示或资源将不胜感激!谢谢!

【问题讨论】:

    标签: database firebase next.js


    【解决方案1】:
    • 当我遇到同样的问题时,我想出了以下代码。看看:-
    import firebase from 'firebase/app';
    import 'firebase/storage';
    import 'firebase/firestore';
    
    export const connectFB = () => {
        const firebaseConfig = {
            apiKey: process.env.apiKey,
            authDomain: process.env.authDomain,
            databaseURL: process.env.databaseURL,
            projectId: process.env.projectId,
            storageBucket: process.env.storageBucket,
            messagingSenderId: process.env.messagingSenderId,
            appId: process.env.appId
        };
    
        if (!firebase.apps.length) {
            firebase.initializeApp(firebaseConfig);
        }
    
        return firebase;
    }
    

    【讨论】:

      【解决方案2】:

      使用.env 文件存储所有凭据并在运行时直接使用它来获取实际上非常轻松。

      试试这个https://github.com/vercel/next.js/discussions/14420#discussioncomment-29816

      【讨论】:

        猜你喜欢
        • 2023-02-20
        • 2017-09-27
        • 2020-06-08
        • 2018-09-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-02-11
        • 2014-05-24
        相关资源
        最近更新 更多