我正在尝试在NodeJs中添加SSE(服务器推送事件),但当我使用
我已经在Github、StackOverflow上找到了很多关于此问题的帖子,在这些帖子中都提到在每个
请问是否有任何方法可以使其工作? 服务端代码:
res.write()
发送响应时,数据不会被发送,只有在写入res.end()
之后,所有数据才会同时发送。我已经在Github、StackOverflow上找到了很多关于此问题的帖子,在这些帖子中都提到在每个
res.write()
之后使用res.flush()
,但这对我也没有起作用,而且我没有显式地使用任何压缩模块。请问是否有任何方法可以使其工作? 服务端代码:
const express = require('express')
const app = express()
app.use(express.static('public'))
app.get('/countdown', function(req, res) {
res.writeHead(200, {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
'Connection': 'keep-alive'
})
countdown(res, 10)
})
function countdown(res, count) {
res.write("data: " + count + "\n\n")
if (count)
setTimeout(() => countdown(res, count-1), 1000)
else
res.end()
}
app.listen(3000, () => console.log('SSE app listening on port 3000!'))
客户端代码
<html>
<head>
<script>
if (!!window.EventSource) {
var source = new EventSource('/countdown')
source.addEventListener('message', function(e) {
document.getElementById('data').innerHTML = e.data
}, false)
source.addEventListener('open', function(e) {
document.getElementById('state').innerHTML = "Connected"
}, false)
source.addEventListener('error', function(e) {
const id_state = document.getElementById('state')
if (e.eventPhase == EventSource.CLOSED)
source.close()
if (e.target.readyState == EventSource.CLOSED) {
id_state.innerHTML = "Disconnected"
}
else if (e.target.readyState == EventSource.CONNECTING) {
id_state.innerHTML = "Connecting..."
}
}, false)
} else {
console.log("Your browser doesn't support SSE")
}
</script>
</head>
<body>
<h1>SSE: <span id="state"></span></h1>
<h3>Data: <span id="data"></span></h3>
</body>
</html>
解决方案 - 我使用了 nginx 作为反向代理,所以出现了问题。我尝试了这个解决方案,它起作用了 :)