Reputation: 59
I have created a server in node.js using express module. It exposes a get api which is used to send events to the client at regular intervals via the open connection which is always kept alive.
const cors = require('cors');
const app = express();
app.use(cors());
const port = 3001;
app.get('/sse-server', function (request, response) {
response.status(200).set({
"connection": "keep-alive",
"cache-control": "no-cache",
"content-Type": "text/event-stream"
});
let data = { name: "Mithoon Kumar"}
setInterval(()=>{ response.write(JSON.stringify(data));}, 0)
})
app.listen(port, () => console.log(`Example app listening on port ${port}!`))
Also I have created a client in node.js which is using eventsource to receive server sent events
console.log("EventSource", EventSource);
const eventSource = new EventSource('http://127.0.0.1:3001/sse-server');
eventSource.onopen = (event) => {
console.log("event", event);
};
eventSource.onerror = (error) => {
console.log("error", error);
}
eventSource.onmessage = (message) => {
console.log("message", message);
}
The problem is onmessage method is never fired. If I open the link (http://127.0.0.1:3001/sse-server) in chrome browser it displays the messages on the page.
Upvotes: 2
Views: 2895
Reputation: 59
I editted the line in which the server was writing data and it started working.
setInterval(()=>{ response.write(`data: Hello world!\n\n`)}, 0)
Upvotes: 0
Reputation: 1848
Apparently, EventSource
only work with specific format which is define in its documentation. As you can see in this example, the message data should be sent in a data: [YOUR_DATA]\n\n
format.
You should use something like this on your server side :
app.get('/event-stream', (req, res) => {
res.status(200).set({
"connection": "keep-alive",
"cache-control": "no-cache",
"content-Type": "text/event-stream"
});
let data = { name: "Mithoon Kumar" }
const intervalId = setInterval(() => {
res.write(`data: ${JSON.stringify(data)}\n\n`);
}, 1000);
req.on('close', () => {
clearInterval(intervalId);
});
});
Upvotes: 6