gpt4 book ai didi

javascript - SSE 和 NodeJS Express

转载 作者:行者123 更新时间:2023-11-28 19:55:08 25 4
gpt4 key购买 nike

无法将 SSE 事件获取到浏览器中的文件。

这是服务器代码(表达):

app.all('/callme', function(req, res){
res.writeHead(200, {
'Connection': 'keep-alive',
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache'
});

setInterval(function(){
console.log('writing');
res.write((new Date()).toString() + '\n');
}, 1000);
})

这是客户端代码:

var source = new EventSource('/events');
source.onmessage = function(e) {
document.body.innerHTML += e.data + '<br>';
};

我在客户端上使用 XHR 使用相同的服务器代码,它可以工作。服务器似乎正确发送数据,但没有在浏览器中被触发。

我已阅读 JavaScript EventSource SSE not firing in browser 似乎不适用于此处,因为我没有运行会影响它的防病毒软件。

最佳答案

您的事件格式似乎不正确

你希望它的格式像这样

res.write("id: " + Date.now() + "\ndata: " + message + "\n\n");
<小时/>

另外,看看这个

node-easysseeasysse-client

关于javascript - SSE 和 NodeJS Express,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22738942/

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