我试图在我的node js项目中使用firebase-admin。下面是我主页的代码:
const functions = require('firebase-functions');
const express = require('express');
const ejs = require('ejs');
var firebase = require('firebase-admin');
const app = express();
// const firebaseApp = firebase.initializeApp(
// functions.config().firebase
// );
app.set('view engine', 'ejs');
app.set('views', './views');
app.use('/', require('./routes/index'));
app.use('/getPosts', require('./routes/posts'));
app.use('/tests', require('./routes/tests'));
exports.app = functions.https.onRequest(app);
exports.firebaseApp = function(){
return firebase.initializeApp(
functions.config().firebase
);
}
文件代码- ./ routes / tests 如下:
const functions = require('firebase-functions');
var express = require('express');
var router = express.Router();
var firebase = require('firebase-admin');
//
// const firebaseApp = firebase.initializeApp(
// functions.config().firebase
// );
const firebaseApp = require('../index.js').firebaseApp;
function getPosts(){
const ref = firebaseApp.database().ref('users');
return ref.once('value').then(snap => snap.val());
}
router.get('/', (req, res, next) => {
getPosts().then(posts => {
res.json(posts);
});
});
module.exports = router;
问题是,当我访问http://localhost:5000/getPosts
时,显示为 TypeError:无法读取未定义的属性'database'。这里的障碍是什么?
添加
firebase.initializeApp(
functions.config().firebase
);
在每个布局页面中都不是一个好主意,因为它将多次初始化firebase。 我该如何解决这个问题?