服务器发送事件/ EventSource与node.js(express) [英] Server Sent Event / EventSource with node.js (express)

查看:448
本文介绍了服务器发送事件/ EventSource与node.js(express)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

正如你所看到的,我已经注释掉了这些帖子,但最终我想使用testdata JSON本身就是这样的:

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

客户端如下所示:

<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.

推荐答案

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

Try sending proper JSON (testdata isn't quoted in your output):

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

但最好是:

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

这篇关于服务器发送事件/ EventSource与node.js(express)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆