使用Express从Firebase数据库获取数据

时间:2018-02-03 11:41:05

标签: javascript node.js firebase express firebase-realtime-database

我想从Firebase数据库中检索数据。

我已经初始化了我的 server.js

var http = require("http");

var firebase = require("firebase");
var express = require("express");
var app = express();
var routerProj = require("./routes/routes");
var bodyParser = require("body-parser");
var port = 8080; // set our port
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
var server = app.listen(port);

app.use(bodyParser.json());
var config = {
  apiKey: "XXXXXXXXXXXXXXXX",
  authDomain: "datatable-18f93.firebaseapp.com",
  databaseURL: "https://datatable-18f93.firebaseio.com",
  projectId: "datatable-18f93",
  storageBucket: "datatable-18f93.appspot.com",
  messagingSenderId: "282475200118"
};
const db = firebase.initializeApp(config);
app.use("/v1", routerProj);

console.log("Server running at http://127.0.0.1:8000/");
module.exports.db = db.database(); //this doesnt have to be database only

然后在我的 router.js 中,我按如下方式定义我的获取路径:

var express = require("express"); // call express
var router = express.Router(); // get an instance of the express Router
var admin = require('firebase-admin');

router
  .route("/")
  .get(function (req, res, err) {

    // Get a database reference to our posts
    var db = admin.database();
    var ref = db.ref("/restau");

    // Attach an asynchronous callback to read the data at our posts reference
    ref.on("value", function (snapshot) {
      console.log(snapshot.val());
    }, function (errorObject) {
      console.log("The read failed: " + errorObject.code);
    });
  });
module.exports = router;

在Postman中获取此地址的请求:http://localhost:8080/v1我收到此错误:

  

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

但是我已经在 server.js 中初始化了数据库连接,为什么我会收到此错误?

1 个答案:

答案 0 :(得分:2)

我相信您只需要Firebase Admin SDK进行初始化,请参阅

https://firebase.google.com/docs/admin/setup#add_firebase_to_your_app

,过程如下:

var admin = require('firebase-admin');

var serviceAccount = require('path/to/serviceAccountKey.json'); // Or your config object as above.

admin.initializeApp({
  credential: admin.credential.cert(serviceAccount), // Or credential
  databaseURL: 'https://<DATABASE_NAME>.firebaseio.com'
});