我正在尝试使用SSE将JSON数据发送到浏览器,但似乎做不对,也不知道为什么。
服务器端代码如下:
正文:如您所见,我已经注释掉了帖子的内容,但是最终我想要像这样使用testdata作为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);
});
正文:如您所见,我已经注释掉了帖子的内容,但是最终我想要像这样使用testdata作为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>
我看到了控制台日志,但没有看到警报。