繁体   English   中英

服务器发送的事件不是“文本/事件流”

[英]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 来确认。)

在 24hours.html 文件的元数据中,我添加了以下内容:

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

删除它,这是不正确的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM