Timppe
Timppe

Reputation: 113

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.

Upvotes: 8

Views: 11385

Answers (1)

robertklep
robertklep

Reputation: 203241

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

Upvotes: 10

Related Questions