问题描述
我想将Server Sent Events(SSE)添加到在nodeJS(Express)上运行的项目中。首先,我使用了以下代码:https://github.com/hnasr/javascript_playground/blob/master/server-sent-events/index.js。当单独运行该示例代码时,它的工作原理就像一个魅力,但是当我将代码合并到我的(更大)项目中时,出现了一些我无法解决的错误。我希望你能帮助我。我认为搞乱了routes文件夹中的代码,不确定是否如此。
我将带有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++}\n\n`);
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)
注意:我尚未创建“ 24hours-events” html文件
在隔离的SSE测试版本中,我在其后添加了sse.onmessage = console.log
,并记录了服务器事件。
如果不清楚,并且需要更多信息来回答这个问题,那么我很高兴收到您的来信。
解决方法
app.get("http://localhost:3000/24hours",(req,res) => {
在定义路线时,您只应指定路径,而不要指定完整的URL:
app.get("/24hours",res) => {
正在接收的HTML可能是404页。 (您应该在网络面板中查看,或直接打开http:// localhost:3000 / 24hours进行确认。)
在24hours.html文件的元数据中,我添加了以下内容:
<meta http-equiv="Content-Type" content="text/event-stream" charset="utf-8" />
删除它,这是不正确的。