node.js - express.js 未流式传输分块 'text/event-stream' 响应

标签 node.js express event-stream

我正在尝试从express.js 端点发送 SSE text/event-stream 响应。我的路线处理程序如下所示:

function openSSE(req, res) {
  res.writeHead(200, {
    'Content-Type': 'text/event-stream; charset=UTF-8',
    'Cache-Control': 'no-cache',
    'Connection': 'keep-alive',
    'Transfer-Encoding': 'chunked'
  });

  // support the polyfill
  if (req.headers['x-requested-with'] == 'XMLHttpRequest') {
    res.xhr = null;
  }

  res.write(':' + Array(2049).join('\t') + '\n'); //2kb padding for IE
  res.write('id: '+ lastID +'\n');
  res.write('retry: 2000\n');
  res.write('data: cool connection\n\n');

  console.log("connection added");
  connections.push(res);
}

稍后我再打电话:

function sendSSE(res, message){
    res.write(message);
    if (res.hasOwnProperty('xhr')) {
        clearTimeout(res.xhr);
        res.xhr = setTimeout(function () {
          res.end();
          removeConnection(res);
        }, 250);
    }
}

我的浏览器发出并保存请求: enter image description here

没有任何响应被推送到浏览器。我的事件都没有被解雇。如果我杀死express.js服务器。响应突然耗尽,每个事件都会立即到达浏览器。 enter image description here

如果我更新代码以在 res.write(message) 行之后添加 res.end() 它会正确刷新流,但随后会回退到事件轮询并且不传输响应。 enter image description here

我尝试在响应的头部添加填充,例如 res.write(':' + Array(2049).join('\t') + '\n'); 正如我从其他 SO 帖子中看到的那样,它可以触发浏览器耗尽响应。

我怀疑这是express.js 的问题,因为我之前曾将此代码与 Node native http 服务器一起使用,并且它工作正常。所以我想知道是否有某种方法可以绕过express对响应对象的包装。

最佳答案

这是我在项目中使用的代码。

服务器端:

router.get('/listen', function (req, res) {
    res.header('transfer-encoding', 'chunked');
    res.set('Content-Type', 'text/json');

    var callback = function (data) {
        console.log('data');
        res.write(JSON.stringify(data));
    };

    //Event listener which calls calback.
    dbdriver.listener.on(name, callback);

    res.socket.on('end', function () {
        //Removes the listener on socket end
        dbdriver.listener.removeListener(name, callback);
    });
});

客户端:

xhr = new XMLHttpRequest();
xhr.open("GET", '/listen', true);
xhr.onprogress = function () {
    //responseText contains ALL the data received
    console.log("PROGRESS:", xhr.responseText)
};
xhr.send();

关于node.js - express.js 未流式传输分块 'text/event-stream' 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29807834/

相关文章:

node.js - 如何从 Node 10.4.1 中的 RxJS 6.2.1 导入 fromPromise

javascript - Multer 尝试创建一个已存在的新文件夹

elasticsearch - AWS Elasticsearch 作为事件存储

node.js - req.session undefined with Redis/Express

Javascript : promise chain vs. 异步/等待?

javascript - Node.js 使用 setTimeout() 暂停和恢复流

node.js - Node js 中的“条件 hell ”

express - Express.js : how to handle “Error: ENOENT, unlink” errors?

java - Drools Fusion 持续时间和时间戳,为什么不起作用?

python - Docker 图像中的 nginx 缓冲 flask 事件流