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.
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.
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');
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');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With