但在 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 上部署时无法接收数据
发布评论