Ndoejs SSE res.write()不在流中发送数据。

问题描述 投票:0回答:1

我正在尝试在NodeJs中添加SSE(服务器发送事件),但当我使用 res.write() 数据没有被发送,但只有在写了 res.end() 所有的数据都在同一时间发送。

我已经在Github、StackOverflow上找到了很多关于这个问题的帖子,而且到处都提到要使用 res.flush() 每次 res.write() 但这对我来说也是行不通的,我也没有明确使用任何压缩模块。

服务器端代码

谁能告诉我有什么办法可以让这个工作。

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的反向代理,所以才会发生这种情况,所以我试了这个解决方案,它的工作:)

事件源服务器-通过Nginx发送事件

node.js server-sent-events
1个回答
1
投票

如果你的Express服务器在防火墙或代理服务器后面,他们通常会等到服务器关闭连接后再发送整个响应。 相反,你需要在浏览器和服务器之间建立一个连接,以使 'Connection': 'keep-alive'.

© www.soinside.com 2019 - 2024. All rights reserved.