Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Server Sent Event / EventSource with node.js (express)

I'm trying to send JSON data to the browser with SSE but I can't seem to get it right and I don't know why.

Server side looks like this:

var express     = require("express"),
    app         = express(),
    bodyParser  = require('body-parser');

app.use(express.static(__dirname + '/'));
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

var testdata = "This is my message";

app.get('/connect', function(req, res){
    res.writeHead(200, {
      'Connection': 'keep-alive',
      'Content-Type': 'text/event-stream',
      'Cache-Control': 'no-cache'
    });

    setInterval(function(){
      console.log('writing ' + testdata);
      res.write('data: {"msg": '+ testdata +'}\n\n');
    }, 1000);
});

/*
app.post('/message', function(req, res) {
  testdata = req.body;
});
*/

var port = 8080;
app.listen(port, function() {
  console.log("Running at Port " + port);
});

As you can see I've commented out the post stuff but eventually I would want to use testdata as JSON itself like this:

res.write('data: ' + testdata + '\n\n');

Client side looks like this:

<script>
    var source = new EventSource('/connect');
    source.onmessage = function(e) {
        var jsonData = JSON.parse(e.data);
        alert("My message: " + jsonData.msg);
    };
</script>

I see the console logs but not the alert.

like image 931
Timppe Avatar asked Jul 29 '15 12:07

Timppe


People also ask

What is server-sent events node JS?

Server-Sent Events (SSE) is a Web standard that allows a server application to send data to the client. Concretely, a browser can subscribe to a stream of events generated by a server, receiving updates whenever a new event occurs. This feature makes it possible to build a more reactive application.

How are server-sent events implemented?

The server-side event stream syntax is simple. Set the "Content-Type" header to "text/event-stream". Now you can start sending event streams. header('Content-Type: text/event-stream');


1 Answers

Try sending proper JSON (testdata isn't quoted in your output):

res.write('data: {"msg": "'+ testdata +'"}\n\n');

But preferably:

res.write('data: ' + JSON.stringify({ msg : testdata }) + '\n\n');
like image 195
robertklep Avatar answered Oct 04 '22 13:10

robertklep