如何在服务器端运行firebase?

Par*_*roi 3 javascript node.js firebase server firebase-realtime-database

我想使用 firebase 作为我的服务器的数据库服务,android 应用程序将向其发送请求。我希望服务器检索数据而不是 Android 应用程序,因为我想在将数据发送回客户端(应用程序)之前进行一些处理。

我的节点代码(index.js):

const express = require('express')
const app = express()

var port = process.env.PORT || 10000

firebase = require('./firebase') // I added this cuz I can't use <script> tag here

// Initialize Firebase
var config = {
    apiKey: "AIzaSynotgonnatell2Q-kwk85XrCyNnc",
    authDomain: "hnotgonnatell.firebaseapp.com",
    databaseURL: "https://hnotgonnatell.firebaseio.com",
    projectId: "notgonnatell",
    storageBucket: "",
    messagingSenderId: "699935506077"
};

firebase.initializeApp(config);

var database = firebase.database()

ref = database.ref("some_table")

data = {
    name : "my name",
    number : "2938019283"
}

app.get('/', function(req, res){
    ref.push(data)
    res.send("hello")
})

app.listen(port)
Run Code Online (Sandbox Code Playgroud)

我无法使用,<script src="https://www.gstatic.com/firebasejs/4.12.1/firebase.js"></script>因为我没有从客户端连接到 firebase。因此,我从https://www.gstatic.com/firebasejs/4.12.1/firebase.js复制了代码,并使用require(). 当我运行 index.js 时,我得到:

firebase.initializeApp(config);
         ^

TypeError: firebase.initializeApp is not a function
    at Object.<anonymous> (E:\workspace_javascript\firebase_try\index.js:24:10)
    at Module._compile (module.js:571:32)
    at Object.Module._extensions..js (module.js:580:10)
    at Module.load (module.js:488:32)
    at tryModuleLoad (module.js:447:12)
    at Function.Module._load (module.js:439:3)
    at Module.runMain (module.js:605:10)
    at run (bootstrap_node.js:422:7)
    at startup (bootstrap_node.js:143:9)
    at bootstrap_node.js:537:3
Run Code Online (Sandbox Code Playgroud)

当我通过返回一个包含 firebase 代码的 html 来运行它时,效果很好<script>

Gho*_*ydr 5

  1. 从 NPM 安装 firebase

      npm install --save firebase-admin
    
    Run Code Online (Sandbox Code Playgroud)
  2. 初始化 firebase

      var admin = require('firebase-admin');
    
      var serviceAccount = require('path/to/serviceAccountKey.json');
    
      admin.initializeApp({
        credential: admin.credential.cert(serviceAccount),
        databaseURL: 'https://<DATABASE_NAME>.firebaseio.com'
      });
    
    Run Code Online (Sandbox Code Playgroud)

源代码:https: //firebase.google.com/docs/admin/setup