javascript - 服务器使用 node.js (express) 发送事件/事件源

标签 javascript json node.js express server-sent-events

我正在尝试使用 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);
});

如您所见,我已经注释掉了帖子内容,但最终我想像这样将测试数据用作 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');

关于javascript - 服务器使用 node.js (express) 发送事件/事件源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31700336/

相关文章:

python - django,使用 ugettext_lazy 时出现 "is not JSON serializable"?

mysql - 为什么 sails.js 启动失败?

javascript - ibm bluemix nodejs 和 websockets 在客户端持续关闭

javascript - 如何配置数据表,以便它根据创建的日期对记录进行排序(描述)?

javascript - 在 JavaScript 中获取今天的从 - 到时间戳

java - 在 elasticsearch 响应中更改字段名称

sql-server - 如何在 SQL Server 列中存储超过 varchar(max) 的非常大的数据?

javascript - Node.js 中的多个函数

javascript - 检查包含对象作为数组的数组中的重复项

javascript - JQuery:在动态创建的元素上添加事件处理程序(动画)