我已经弄清楚了如何从Firebase中保存和检索日期,但是在将JSON保存到变量中时遇到了问题。我已经将变量设置为usersDB,但是当我console.log()变量时,它以 undefined
注销//firebase setup
var db = admin.database();
var ref = db.ref("server/saving-data/fireblog"); //var for databaseURL
//firebase
var usersRef = ref.child("users"); //where I am pulling the data from
var usersDB // init var
ref.on("value", function(snapshot) {
console.log(snapshot.val()); // logs the way I want it
usersDB = snapshot.val(); // trying to save json
}, function (errorObject) {
console.log("The read failed:" + errorObject.code);
})
console.log(usersDB) // logs undefined
app.get("", function(req, res) {
res.render("index", {users : usersDB});
})
app.post("/", function(req, res) {
console.log(req.body.user.username);
usersRef.child(req.body.user.username).set({
name: req.body.user.name,
email: req.body.user.email,
});
res.redirect('/');
});
答案 0 :(得分:0)
尝试将变量传递到另一个函数中并将其保存在其中:
ref.on("value", function(snapshot) {
console.log(snapshot.val()); // logs the way I want it
func_(snapshot.val()); // trying to save json
}, function (errorObject) {
console.log("The read failed:" + errorObject.code);
})
function func_(json){
console.log(json) // logs undefined
}