EventSource 在本地工作,但在 Heroku 上部署时无法接收数据

编程入门 行业动态 更新时间:2024-10-02 20:27:16

EventSource 在本地工作,<a href=https://www.elefans.com/category/jswz/34/1771274.html style=但在 Heroku 上部署时无法接收数据"/>

EventSource 在本地工作,但在 Heroku 上部署时无法接收数据

我们有一个带有 ExpressJS 服务器的 Nuxt 项目,它使用 EventSource 从服务器获取流数据。这在本地主机上运行良好,但是当部署在 Heroku 上时,没有收到任何数据,并且连接在 55 秒后超时并出现此错误:

GET  net::ERR_INCOMPLETE_CHUNKED_ENCODING 200 (OK)

服务器接收到请求并使用 res.write 发送响应,但客户端永远看不到它们。

这里是客户端代码:

this.evtSource = new EventSource('/api/sse');
this.evtSource.onerror = err => {
  console.error('EventSource error', err);
}

this.evtSource.onmessage = e => {
  if (e.data === '[DONE]') {
    this.evtSource.close();
  } else {
    console.log('message', e);
    this.output.push(e);
  }
};

在服务器上:

server.get('/sse', (req, res) => {
    console.log('enter sse');
    console.log('res', res);

    res.setHeader('Cache-Control', 'no-cache');
    res.setHeader('Content-Type', 'text/event-stream');
    res.setHeader('Access-Control-Allow-Origin', '*');
    res.setHeader('Connection', 'keep-alive');
    res.flushHeaders(); // flush the headers to establish SSE with client

    let counter = 0;
    const intervalId = setInterval(() => {
        counter++;
        console.log('will res.write. counter', counter);
        res.write(`data: ${JSON.stringify({ text: 'hi there', num: counter })}\n\n`);
        if (counter >= 10) {
            // this is also what OpenAI uses to signal end of stream 
            res.write('data: [DONE]\n\n');
            clearInterval(intervalId);
            // res.end(); // terminates SSE session
            return;
        }
    }, 800);

    // If client closes connection, stop sending events
    res.on('close', () => {
        console.log('client dropped me');
        clearInterval(intervalId);
        res.end();
    });
});

重现问题的测试项目:

在此处查看此问题: /

回答如下:

更多推荐

EventSource 在本地工作,但在 Heroku 上部署时无法接收数据

本文发布于:2024-05-30 13:38:45,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1770554.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:但在   数据   工作   EventSource   Heroku

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!