8

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.

Timppe
  • 113
  • 1
  • 1
  • 7
  • Got the stuff working with another question of mine, see full code on my other question: http://stackoverflow.com/questions/31653481/how-do-i-modify-the-page-im-serving-in-node-js – Timppe Jul 30 '15 at 12:17
  • I was just looking for an example like this, very useful! – Manjar Mar 18 '21 at 10:07

1 Answers1

10

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');
robertklep
  • 198,204
  • 35
  • 394
  • 381
  • I had it quoted at some stage but I might have had other failures at that time :) thanks! I'm getting my messages and bigger JSONs through now. – Timppe Jul 30 '15 at 08:45