![](/img/trans.png)
[英]How to query Firebase with Node.js and "firebase-admin" SDK?
[英]How to connect Firebase to a Node.JS project?
我最初開發了一個沒有 NodeJS 的應用程序。 但后來我連接了 Node.JS,因為我需要使用 listCollections() 獲取數據庫中的所有 collections。 在連接Node Firebase之前,我在Firebase.js文件中對其進行了初始化。 現在我添加了 Node.JS 並建立了 firebase-admin 連接,如示例所示。 但是在啟動服務器時,錯誤是
FirebaseAppError:默認的 Firebase 應用程序不存在。 確保在使用任何 Firebase 服務之前調用 initializeApp()。 如何正確連接 Firebase?
server.js:
const express = require("express");
const admin = require("firebase-admin");
const db = admin.firestore();
const app = express();
const PORT = 3000;
app.use(express.static("public"));
app.get("/", (req, res) => {
res.send("Hello World!");
});
app.listen(PORT, () => console.log(`Server listening on port: ${PORT}`));
db.listCollections()
.then((snapshot) => {
snapshot.forEach((snaps) => {
console.log(snaps["_queryOptions"].collectionId); // LIST OF ALL COLLECTIONS
});
})
.catch((error) => console.error(error));
firebase.js:
const firebaseConfig = {
apiKey: "...",
authDomain: "..",
projectId: "...",
storageBucket: "...",
messagingSenderId: "...",
appId: "...",
measurementId: "...",
};
firebase.initializeApp(firebaseConfig);
var db = firebase.firestore();
If I understand correctly you have client-side code that uses the regular Firebase JavaScript SDK for web clients, and then you have server-side code where you use the Firebase Admin SDK for Node.js.
由於這些代碼彼此完全獨立運行,因此您需要分別初始化每個 SDK。 當您正確初始化客戶端 SDK 時,您沒有在任何地方初始化 Node.js SDK - 所以您需要為此添加代碼。 要了解如何執行此操作,請參閱有關初始化管理員 SDK的 Firebase 文檔。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.