0

Cannot get SSE events to file in browser.

This the server code (express):

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);
})

This the client code:

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

I use this same server code using XHR on the client and it works. The server appears to be sending the data correctly, but not getting fired in the browser..

I've already read JavaScript EventSource SSE not firing in browser Doesn't seem to apply here, as I'm not running anti-virus that would affect it.

Community
  • 1
  • 1
C B
  • 12,482
  • 5
  • 36
  • 48

1 Answers1

4

It looks like the formatting on your event isn't correct

You want it formatted like this

res.write("id: " + Date.now() + "\ndata: " + message + "\n\n");

Also, check out this

node-easysse and easysse-client

mikemaccana
  • 110,530
  • 99
  • 389
  • 494
Mulan
  • 129,518
  • 31
  • 228
  • 259