我正在尝试利用node.js中的服务器发送事件,以便我的应用程序可以向浏览器触发事件以更新页面上的数据。
我创建了三个文件 1. class携带server -sent方法 2.用于流式传输请求的路由 3.从该文件中调用sseevent
module.exports = function (req, res, next) {
//SetTimeout
//req.socket.setTimeout(Infinity);
res.writeHead(200, {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
'Connection': 'keep-alive'
});
res.sseSend = function(data,event) {
var d = new Date(),
events = ((undefined === event) ? 'message' : event);
res.write('id: ' + d.getMilliseconds() + '\n');
res.write("data: " + JSON.stringify(data) + "\n\n");
res.write("event:" + events);
};
next(); };
import express from "express";
let router = express.Router();
import config from "../../config/configuration";
import sse from "../../class/server-sentEvent.class";
class ServerSent {
constructor(app) {
this.app = app;
this.init();
}
init() {
this.setupBase();
this.sseEvent();
}
setupBase() {
this.app.use(sse);
this.app.use(config.basePath, router);
}
sseEvent(){
let _this = this;
router.get('/stream', function(req, res) {
res.sseSend({'name':'FirstUser'},'update');
});
}
}
module.exports = (app) => {
return new ServerSent(app);
};
import express from "express";
let router = express.Router();
import config from "../../config/configuration";
import sse from "../../class/server-sentEvent.class";
class Read {
constructor(app) {
this.app = app;
this.init();
}
init() {
this.getSecondUser();
}
getSecondUser() {
router.post('/getAll', (req, res, next) => {
res.sseSend({'name':'SecondUser'},'update');
res.json(response);
});
}
}
从Read Class,ssesend Event没有被解雇,因此无法找到方法。
我尝试的事情: