Skip to content

Instantly share code, notes, and snippets.

@jaguilar87
Last active October 23, 2018 12:06
Show Gist options
  • Save jaguilar87/a2462f6d7861af50275ba931245a2f2f to your computer and use it in GitHub Desktop.
Save jaguilar87/a2462f6d7861af50275ba931245a2f2f to your computer and use it in GitHub Desktop.
A test for Server Sent Events
<html>
<head>
<title>SSE example</title>
</head>
<body>
<h2>Messages:</h2>
<pre id="response"></pre>
<input id="message"> <button id="btnSubmit">Broadcast</button>
<script>
// Extremely simplified here, no error handling or anything
document.body.onload = function () {
var es = new EventSource('/stream');
es.addEventListener('message', function (e) {
document.getElementById('response').innerHTML += JSON.parse(e.data).msg + '\n';
});
document.getElementById('btnSubmit').addEventListener('click', () => {
const msg = JSON.stringify({ msg: document.getElementById('message').value });
console.log('Sending', msg);
fetch('/stream', {
headers: { 'Content-Type': 'application/json' },
method: 'POST',
body: msg
});
})
}
</script>
</body>
</html>
const express = require('express');
const Sse = require('express-sse');
const sse = new Sse();
exports.getRouter = () => {
const app = new express.Router();
app.get('/stream', sse.init);
app.post('/stream', exports.broadcast);
return app;
};
exports.broadcast = (req, res) => {
sse.send(req.body);
res.send('OK');
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment