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
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'
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With