我想将服务器发送事件(SSE(添加到在nodeJS(Express(上运行的项目中。首先,我使用了以下代码:https://github.com/hnasr/javascript_playground/blob/master/server-sent-events/index.js.这个示例代码在孤立运行时很有魅力,但当我将代码合并到我的(更大的(项目中时,我遇到了一些无法解决的错误。我希望你能帮我。我想把路由文件夹里的代码搞砸了,不确定。
我使用带有express的NodeJ作为我的服务器。文件夹app.js
包含此代码。
#Routing code
var router_price_24h_changes = require('./routes/24hours');
app.use('/24hours', router_price_24h_changes);
#>>>a lot of other (probably unnecessary code)<<<
#Added this
app.get("/24hours-events", (req,res) => {
res.setHeader("Content-Type", "text/event-stream");
send(res);
console.log("Stream")
})
let i = 0;
function send (res) {
console.log("send")
res.write("data: " + `hello!${i++}nn`);
setTimeout(() => send(res), 1000);
}
这就是我的routes-24hours.js
的样子:
var express = require('express');
var router = express.Router();
const fs = require('fs');
router.get('/', function(req, res, next) {
const myHtml = fs.readFileSync('./24hours.html', 'utf-8');
const changes = fs.readFileSync("./changes.json", 'utf-8');
const changes2 = fs.readFileSync("./changes2", 'utf-8');
res.send(myHtml.replace(/data/g, JSON.stringify(({changes ,changes2 }), null, 0)));
});
module.exports = router;
当我从chrome浏览器访问24hours-events
网页时,我键入了这个
let sse = new EventSource("http://localhost:3000/24hours-events");
在控制台日志中,这是响应:
http://localhost:3000/24hours-events 404 (Not Found)
注意:我没有创建一个";24小时事件";html文件
在隔离的SSE测试版本中,我在它之后添加了sse.onmessage = console.log
,它记录了服务器事件。
如果有什么不清楚的地方,需要更多的信息来回答这个问题,我会很高兴收到你的来信。
app.get("http://localhost:3000/24hours", (req,res) => {
在定义路由时,您应该只指定路径,而不是完整的URL:
app.get("/24hours", (req, res) => {
正在接收的HTML可能是一个404页面。(您应该查看网络面板,或者打开http://localhost:3000/24hours直接确认。(
在24hours.html文件的元数据中,我添加了以下内容:
<meta http-equiv="Content-Type" content="text/event-stream" charset="utf-8" />
删除它,这是不正确的。