服务器发送的事件不是 "text/event-stream"

Server Sent Events are not "text/event-stream"

我想将服务器发送事件 (SSE) 添加到我在 nodeJS (Express) 上运行的项目中。作为开始,我使用了这个代码:https://github.com/hnasr/javascript_playground/blob/master/server-sent-events/index.js。当 运行 孤立地使用此示例代码时,它就像一个魅力,但是当我将代码合并到我的(更大的)项目中时,我遇到了一些我无法解决的错误。我希望你能帮助我。我认为路线文件夹中的代码搞砸了,但不确定。

我使用带有 express 的 NodeJs 作为我的服务器。 文件夹 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)

注意:我还没有创建“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 来确认。)

In the metadata of the 24hours.html file I have added this:

<meta http-equiv="Content-Type" content="text/event-stream" charset="utf-8" />

删除那个,不正确。