Server Sent Event / EventSource with node.js (express)

Server Sent Event / EventSource with node.js (express)

我正在尝试使用 SSE 将 JSON 数据发送到浏览器,但我似乎无法正确发送,我也不知道为什么。

服务器端看起来像这样:

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

如您所见,我已经注释掉了 post 内容,但最终我想像这样将测试数据用作 JSON 本身:

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

客户端看起来像这样:

<script>
    var source = new EventSource('/connect');
    source.onmessage = function(e) {
        var jsonData = JSON.parse(e.data);
        alert("My message: " + jsonData.msg);
    };
</script>

我看到控制台日志,但不是警报。

尝试发送正确的 JSON(testdata 未在您的输出中引用):

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

但最好是:

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