html5的岩石节点js服务器发送事件SSE示例不起作用

链接到文章: http : //www.html5rocks.com/en/tutorials/eventsource/basics/

在这个例子中,node.js SSE服务器不工作。 我最终打开了/events连接,但浏览器没有收到任何响应。

Chrome开发工具prnt scrn

SSE-server.js

 var http = require('http'); var sys = require('sys'); var fs = require('fs'); http.createServer(function(req, res) { //debugHeaders(req); if (req.headers.accept && req.headers.accept == 'text/event-stream') { if (req.url == '/events') { sendSSE(req, res); } else { res.writeHead(404); res.end(); } } else { res.writeHead(200, {'Content-Type': 'text/html'}); res.write(fs.readFileSync(__dirname + '/sse-node.html')); res.end(); } }).listen(8000); 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, (new Date()).toLocaleTimeString()); }, 5000); constructSSE(res, id, (new Date()).toLocaleTimeString()); } function constructSSE(res, id, data) { res.write('id: ' + id + '\n'); res.write("data: " + data + '\n\n'); } function debugHeaders(req) { sys.puts('URL: ' + req.url); for (var key in req.headers) { sys.puts(key + ': ' + req.headers[key]); } sys.puts('\n\n'); } 

SSE-node.html

 <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> </head> <body> <script> var source = new EventSource('/events'); source.onmessage = function(e) { document.body.innerHTML += e.data + '<br>'; }; </script> </body> </html> 

问题出在服务器上。 在我的情况下,我使用iisnode节点包使用节点与IIS。 为了解决这个问题,我需要像这样在web.config中configurationiisnode:

 <iisnode flushResponse="true" /> 

之后,一切正常。 其他人也可能从这里开始,但是apache和nginx可能有类似的configuration要求。

为什么在sendSSE函数的最后注释掉res.end()? 这是实际将响应发送到浏览器的方法。

我已经尝试了这个代码,并且正在为我工​​作,因为您不使用ngnix或任何其他服务器作为您的节点实例的代理我相信问题是与您的机器,如果您有防火墙或反病毒运行,停止它,并再次尝试或任何其他软件,可能会拦截你的请求和水库。

确保您已经将相同名称的HTML文件保存在同一目录下的sse-node.html中。 其他的事情可能是确保您的本地机器上的8000端口是打开的,没有人正在使用它。 或更改端口并重新运行sse-server.js。 它为我工作。