[英]Is it possible to access firebase on both server side and client side in NodeJS?
I'm working an app that need to access the firebase database on both client-side (to catch "on" event to grab recently added data) and server-side (to add record to the database).我正在开发一个需要在客户端(捕捉“on”事件以获取最近添加的数据)和服务器端(将记录添加到数据库)上访问 firebase 数据库的应用程序。 I'm not sure that I did it correctly that use 2 db instances are required on both client and server OR create 1 on the server and use it on the client cause I got a warning on the local side saying that Firebase is already defined in the global scope.
我不确定我是否正确地在客户端和服务器上都需要使用 2 个 db 实例,或者在服务器上创建 1 并在客户端上使用它,因为我在本地收到警告说 Firebase 已经在全球 scope。
This is how I declare the db instance on server-side , this works perfectly fine:这就是我在 server-side 声明 db 实例的方式,效果很好:
var admin = require("firebase-admin");
var serviceAccount = require("../config/sterminal-0000-firebase-adminsdk-bvuit-ce5ee771bc.json");
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
databaseURL: "https://sterminal-0000.firebaseio.com"
});
module.exports.admin = admin;
...
const {admin} = require('../extra/firebase');
let db = admin.database();
This is how I declare the db instance on client-side :这就是我在客户端声明数据库实例的方式:
Include the libs to pug template将库包含到 pug 模板
script(src="https://www.gstatic.com/firebasejs/7.14.2/firebase-app.js")
script(src="https://www.gstatic.com/firebasejs/7.14.2/firebase-database.js")
script(src="/javascripts/local.js" crossorigin="anonymous")
And in local script :在本地脚本中:
var firebaseConfig = {
apiKey: "AIzaSyCkip7lcHNNodJNhrO5n0Hog5Kvs100000",
authDomain: "sterminal-00000.firebaseapp.com",
databaseURL: "https://sterminal-00000.firebaseio.com",
projectId: "sterminal-8bf73",
storageBucket: "sterminal-00000.appspot.com",
messagingSenderId: "961511900000",
appId: "1:96151100000:web:f3cec40f38f7b7d4000000"
};
firebase.initializeApp(firebaseConfig);
firebase.database().ref("messages").on("child_added", function (snap) {
console.log(snap.val().message);
}); // ----> DOES NOT WORK
I got a warning on local-side :我在本地收到警告:
logger.ts:115 [2020-04-27T18:43:48.559Z] @firebase/app:
Warning: Firebase is already defined in the global scope. Please make sure
Firebase library is only loaded once.
Yes, you can access Firebase Realtime Database from both client-side Node.js and server-side Node.js.是的,您可以从客户端 Node.js 和服务器端 Node.js 访问 Firebase 实时数据库。 But the SDK are separate, and you can't include both of them in a single project.
但是 SDK 是独立的,您不能将它们都包含在一个项目中。 The latter seems to be what is leading to the error you now have.
后者似乎是导致您现在遇到的错误的原因。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.