Server dispatched event / EventSource using node.js (express)

I'm trying to send JSON data to the browser using SSE, but I can't figure out what is correct and I don't know why.

The 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 commented stuff, but ultimately I would like to use testdata as JSON itself, like this:

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

      

The 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 console logs, but no warning.

+3


source to share


1 answer


Try sending correct JSON ( testdata

not listed in your output):

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

      



But preferably:

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

      

+4


source







All Articles