express.js不流式处理分块的“文本/事件流”存储库

问题描述 投票:0回答:2

我正在尝试从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);
    }
}

我的浏览器发出并保留请求:“在此处输入图像描述”

没有任何响应被推送到浏览器。我的活动均未触发。如果我杀死了express.js服务器。响应突然耗尽,每个事件立即到达浏览器。“在此处输入图像描述”

如果我更新代码以在res.end()行之后添加res.write(message),则会正确刷新流,但是它会回退到事件轮询,并且不会传输响应。“在此处输入图像描述”

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

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

node.js express event-stream
2个回答
1
投票

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

服务器端:

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();

1
投票

我也正在为此而苦苦挣扎,因此在浏览和阅读后,我通过为响应对象设置一个额外的标题解决了这个问题:

res.writeHead(200, {
  "Content-Type": "text/event-stream",
  "Cache-Control": "no-cache",
  "Content-Encoding": "none"
});

长话短说,当EventSource与服务器协商时,它正在发送Accept-Encoding: gzip, deflate, br标头,这使expressContent-Encoding: gzip标头做出响应。因此,针对此问题有两种解决方案,第一种是在响应中添加Content-Encoding: none标头,第二种是(gzip)压缩响应。

© www.soinside.com 2019 - 2024. All rights reserved.