为什么不能将数据从node.js推送到Firebase?

时间:2018-09-12 12:43:20

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

我从一个使用node.js和Firebase实时数据库开发REST API的项目开始。我一直在努力连接并将数据推送到Firebase。由于我打算使用MVC结构,因此我计划分离出下面的user.js文件中所示的模型。请看一下我的代码:

/* user.js */

function User (id, firstName, lastName) {
    this.id = id;
    this.firstName = firstName;
    this.lastName= lastName;
}

const config = {
    apiKey: "....",
    authDomain: "....",
    databaseURL: "....",
    projectId: "....",
    storageBucket: "....",
    messagingSenderId: "...."
}

const firebase = require('firebase');
firebase.initializeApp(config);
const database = firebase.database();
const userRef = database.ref('/users');

User.prototype.post = () => {
    console.log(this.id);

    //just to test whether the database is connected
    //ref: https://firebase.google.com/docs/database/web/offline-capabilities
    userRef.on("value", function(snap) {
        if (snap.val() === true) {
          console.log("connected");
        } else {
          console.log("not connected");
        }
      });

    userRef.child(this.id).set({
        firstName: this.firstName,
        lastName: this.lastName
    });
}
module.exports = User;

/* index.js */

const User = require('./user')
const express = require('express');
const app = express();
app.use(express.json());

app.get('/users', (req, res) => {
    const {id, firstName, lastName} = req.body;
    const user = new User (id, firstName, lastName);
    //console.log(user);
    user.post();
    res.send("Success!");
}

const port = 3000;
app.listen(port, () => console.log(`Listening on port ${port}`));

当我尝试发送POST请求时,数据没有被推送到Firebase数据库。对于测试数据库是否已连接的代码,我也得到了"not connected"(请参见user.js)。有人可以指导我哪里出问题了吗?任何帮助将不胜感激。

P.S:我应该提一下,当我尝试在单个index.js文件中进行所有操作时,此方法工作正常。但是,我想分离出user.js模型。

0 个答案:

没有答案