Reputation: 1556
I would like to retrieve data from a Firebase Database.
I have initialized my server.js like this:
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
Then in my router.js I define my get route as follows:
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;
In Postman with get request to this adress: http://localhost:8080/v1
I get this error:
Error: The default Firebase app does not exist. Make sure you call initializeApp() before using any of the Firebase services.
But I have initialized database connection in server.js, so why am I getting this error?
Upvotes: 3
Views: 10154
Reputation: 1241
I believe you only need Firebase Admin SDK for initialization, referring to
https://firebase.google.com/docs/admin/setup#add_firebase_to_your_app
and the process goes like :
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'
});
Upvotes: 5