Rub*_*nez 5 javascript node.js express server-sent-events angularjs
我正在使用 MEAN 并且我正在尝试从服务器端接收事件。为此,我使用 EventSource 但它不起作用。
我看到连接是如何打开的,但我没有从服务器收到任何消息。我可以在 Node 控制台中看到消息是如何发送的,但在客户端什么都没有(浏览器控制台)。
当我遵循我找到的所有教程时,我有点迷茫,但是使用完全相同的代码它不起作用。
在客户端,这是我的 AngularJS 代码:
var source = new EventSource('/api/payments/listen');
source.addEventListener('open', function(e) {
console.log('CONNECTION ESTABLISHED');
}, false);
source.addEventListener('message', function (e) {
$scope.$apply(function () {
console.log('NOTIFICATION');
console.log(e.data);
});
}, false);
source.onmessage = function (e) {
console.log('NOTIFICATION!');
console.log(e);
};
source.addEventListener('error', function(e) {
if (e.readyState === EventSource.CLOSED) {
console.log('CONNECTION CLOSED');
}
}, false);
Run Code Online (Sandbox Code Playgroud)
服务器端代码:
exports.listen = function (req, res) {
if (req.headers.accept && req.headers.accept === 'text/event-stream') {
if ( req.url === '/api/payments/listen' ) {
sendSSE(req, res);
}
else {
res.writeHead(404);
res.end();
}
}
else
res.end();
};
function sendSSE(req, res) {
res.writeHead(200, {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
'Connection': 'keep-alive'
});
var id = (new Date()).toLocaleTimeString();
// Sends a SSE every 5 seconds on a single connection.
setInterval(function() {
constructSSE(res, id, data);
}, 5000);
constructSSE(res, id, data);
}
function constructSSE(res, id, data) {
res.write('id: ' + id + '\n');
res.write('data: ' + JSON.stringify(data) + '\n\n');
}
Run Code Online (Sandbox Code Playgroud)
有什么建议吗?任何提示?
编辑
我不知道是什么导致了这个问题,但我已经使用 Simple-SSE 让它工作了,Simple-SSE 是一个用于服务器端事件的有用的小库。
现在,它按预期工作。
这是那些想要尝试的人的链接:https : //github.com/Lesterpig/simple-sse
谢谢=)
小智 14
希望这可以帮助遇到与我相同问题的任何人。在无法从服务器接收消息之后,我来到了这个问题,尽管我的代码中的所有内容似乎都完全符合预期。看到这个库帮助我挖掘了源代码并找到了我的答案。如果您正在使用任何压缩库,例如我在我的 express 应用程序中,您需要在写入后刷新响应。否则压缩不会像协议期望的那样发送消息。例如 res.write("data:hi\n\n") res.flush()