【发布时间】:2018-02-22 23:51:50
【问题描述】:
当数据被推送到数据库时,我会使用数据流自动更新我的角度材料数据表
这是我的 router.js
router
.route("/")
.get(function (req, res, err) {
// Get a database reference to our posts
var db = admin.database();
var ref = db.ref("/");
// Attach an asynchronous callback to read the data at our posts reference
ref.on("value", function (snapshot) {
var list = [];
snapshot.forEach(function (elem) {
list.push(elem.val());
})
res.send(list);
}, function (errorObject) {
console.log("The read failed: " + errorObject.code);
});
});
router
.route("/")
.post(function (req, res, err) {
console.log(req.body);
// Get a database reference to our posts
var db = admin.database();
var ref = db.ref("/");
// Attach an asynchronous callback to read the data at our posts reference
ref.push(
{
"text": req.body.text
}
);
});
当我运行我的应用程序时,我得到了所有数据,然后当我尝试将数据发布到数据库时,我得到了这个错误:
FIREBASE WARNING: Exception was thrown by user callback. Error: Can't set headers after they are sent.
当我使用once 而不是on 时,我没有收到错误,但由于我需要在每次更新数据库时获取新数据,我应该使用on 来获取数据流。
那么如何使用on 而不出现此错误?
【问题讨论】:
-
.on 绑定一个不会消失的处理程序。 .once 绑定一个消失的处理程序。显然,您想要后一种您已证明有效的解决方案。
-
一个请求不能多次响应,因此监听下一个变化是没有意义的。
-
因为错误试图告诉你,你只能发送一次响应。
-
有一次在添加新数据时不发送更新到前台
-
你不能通过 http 请求来做到这一点。
标签: javascript node.js firebase express