当数据被推送到数据库时,我会使用数据流自动更新我的角度材料数据
这是我的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
?
答案 0 :(得分:0)
当您使用on("value")
附加侦听器时,它将继续侦听数据。这意味着如果数据稍后更改,它也会触发,此时您已经向客户端发送了响应并关闭了套接字。
为防止这种情况发生,您应该使用once("value")
收听:
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.once("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);
res.status(500).send(errorObject.code);
});
});
我还添加了对错误处理程序的响应。
<强>更新强>
如果您想继续向客户端发送更新,您需要保持连接打开。在这种情况下,您不应该调用res.send()
(关闭连接),而是res.write()
(使连接保持打开状态)。见Difference between response.send and response.write in node 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.write(list);
}, function (errorObject) {
console.log("The read failed: " + errorObject.code);
res.status(500).send(errorObject.code);
});
});