gpt4 book ai didi

node.js - 在调用 res.end() 之前,SSE 事件不会到达客户端

转载 作者:行者123 更新时间:2023-12-05 03:53:23 25 4
gpt4 key购买 nike

同样的代码以前可以工作,但我不知道为什么现在不工作了。请帮忙。

我的问题是,当我使用 SSE 进行实时数据共享时。应该在 res.write(data:${JSON.stringify(dataObject)}\n\n) 在调用 res.end() 之前不会发送,并且所有数据都是事件流,并且会立即发送。

response.writeHead(200, {
Connection: "keep-alive",
"Content-Type": "text/event-stream",
"Cache-Control": "no-cache",
"Access-Control-Allow-Origin": '*',
'Content-Encoding':'identity' // this with and without this
});

let syncher= setInterval(() => {
if(response.finished){ // If response ended the interval is cleared
clearInterval(syncher);
return;
}else{
let dataToSend = getEventData(user,event);
if(! dataToSend ){
response.write('data:{close:true}');
clearInterval(syncher);
return;
}
response.write(`data:${JSON.stringify(dataToSend)}\n\n`);
response.flushHeaders(); // Also tried with response.flush()
if(dataToSend.close){
delEventData(user,event);
response.end();
}
}
}, 500);

上面的代码是在服务器端,这也有关闭监听器来关闭连接

const ev = new EventSource(conf.apiUrl+'/getStatus/'+ (userData.id || '') );
let data = '';
ev.onmessage = eventData=>{
data = JSON.parse(eventData.data);
if(!data){
setState('progress '+data.completedSoFar)
return;
}
if(!data.close){

}else{
if(data.success){
console.log('Done Successfully')
ev.close();
}
}

这是我的客户端代码

我不知道为什么当我在互联网上搜索有关此问题的事件监听器没有获取数据流时,我只发现在使用压缩中间件时会出现此问题。我没有在我的应用程序中使用任何压缩中间件。我正在使用 nodejs v11.4.0。我猜想当我发出事件源请求时,chrome 默认添加 gzip 编码,而 Node 正在使用它来将响应编码 header 设置为 gzip 我试图删除并替换它,但没有起作用,这导致了这个问题??

Here is my request and response headers for eventSource request

如果我有任何错误,请原谅我的语法。

感谢您的帮助。干杯!

最佳答案

Nextjs 基本上是 compressing您的数据,使其传输更快。不幸的是,这使得我们无法看到数据,直到我们刷新缓存(我的猜测是渲染行为已经改变,因为压缩改变了内容)。您可以通过在 next.config 中包含 compress: false 来完全禁用压缩。

我找到了 here包括以下 header 可避免特定端点的压缩:res.setHeader("Cache-Control", "no-cache, no-transform");

注意:这会增加带宽/资源使用! HTTP 压缩可以将数据大小减少 70% .

关于node.js - 在调用 res.end() 之前,SSE 事件不会到达客户端,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61676262/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com