Reputation: 261
I have a firebase tree like this :
I want to retrieve this data into a JSON object
I tried the following code but its showing empty on my browser:
const http = require('http');
const firebase = require('firebase');
var config = {
apiKey: "AIzjhjdfkjkfkjkjkfPSFNo3Eb-e2E",
authDomain: "demoapp.firebaseapp.com",
databaseURL: "https://demoapp-54551.firebaseio.com",
projectId: "demoapp-79516",
};
var server = http.createServer((req,res)=>{
if (!firebase.apps.length) {
firebase.initializeApp(config);
}
var db = firebase.database();
var d = {}
res.statusCode = 200;
res.setHeader('Content-Type','text/plain');
var readRef = db.ref('categories');
readRef.once('value', snapshot => {
var key = snapshot.key;
d[key] = [];
d[key].push(snapshot.val());
});
res.end(JSON.stringify(d));
});
server.listen(8080);
My result is empty object like below:
Please help me how to get Firebase data into a JSON string
Upvotes: 2
Views: 1186
Reputation: 599621
It seems you're trying to use the Firebase web/IoT SDK in a Cloud Function: const firebase = require('firebase');
. That won't work.
Instead you should use the Firebase Admin SDK, as shown in all the samples: https://firebase.google.com/docs/functions/get-started#import_the_required_modules_and_initialize
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
var db = admin.database();
Upvotes: 2