Note that there are some explanatory texts on larger screens.

plurals
  1. POhtml5 rocks node js server-sent-events SSE example not working
    primarykey
    data
    text
    <p>link to article: <a href="http://www.html5rocks.com/en/tutorials/eventsource/basics/" rel="noreferrer">http://www.html5rocks.com/en/tutorials/eventsource/basics/</a></p> <p>The node.js SSE server is not working in that example. I end up with an open connection to <code>/events</code>, but no response is received by the browser.</p> <p><img src="https://i.stack.imgur.com/GgoTd.png" alt="Chrome dev-tool prnt scrn"></p> <p><strong>sse-server.js</strong></p> <pre><code>var http = require('http'); var sys = require('sys'); var fs = require('fs'); http.createServer(function(req, res) { //debugHeaders(req); if (req.headers.accept &amp;&amp; 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'); } </code></pre> <p><strong>sse-node.html</strong></p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;meta charset="utf-8" /&gt; &lt;/head&gt; &lt;body&gt; &lt;script&gt; var source = new EventSource('/events'); source.onmessage = function(e) { document.body.innerHTML += e.data + '&lt;br&gt;'; }; &lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload