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.

2
  • Got the stuff working with another question of mine, see full code on my other question: stackoverflow.com/questions/31653481/…
    – Timppe
    Commented Jul 30, 2015 at 12:17
  • I was just looking for an example like this, very useful!
    – Manjar
    Commented Mar 18, 2021 at 10:07

1 Answer 1

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');
1
  • 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
    Commented Jul 30, 2015 at 8:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.