Ndoejs SSE res.write() not sending data in streams

给你一囗甜甜゛ 提交于 2020-05-24 06:54:28

问题


I am trying to add SSE(Server sent events) in NodeJs, But when I am sending response using res.write() the data is not getting sent, but only after writing res.end() all data is being sent at the same time.

I have already found many posts on Github, StackOverflow, regarding this issue and everywhere it is mentioned to use res.flush() after every res.write() but that too isn't working for me, also I am not using any compression module explicitly.

Server-Side Code

Can anyone please tell me is there any way I can make this work.

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!'))

Client-Side Code

<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>

Solution - I was using nginx for reverse proxy that's why it was happening so I tried this solution and it worked :)

EventSource / Server-Sent Events through Nginx


回答1:


If your Express server is behind a firewall or proxy server, they will often wait until the server closes the connection before sending the entire response. Instead, you need to have a connection between the browser and the server that allows the 'Connection': 'keep-alive'.



来源:https://stackoverflow.com/questions/61412538/ndoejs-sse-res-write-not-sending-data-in-streams

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!