When I try to do SSE on express the server stops responding every time after exactly 5 attempts. I would like to have it working indefinitely as it should.
If I leave the page alone after a while this error appears:
"POST http://localhost:3000/api/update net::ERR_EMPTY_RESPONSE"
and on the server:
"MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 message listeners added to [EventEmitter]. Use emitter.setMaxListeners() to increase limit"
Both errors don't appear immediately.
I tried changing headers and sending different statuses but without any effect except breaking even what is working.
I am fairly new to express and node in general, I don't really know what I am doing wrong here.
My server is set-up like this:
app.get("/api/update", (req, res, next) => {
res.status(200).set({
"Content-Type": "text/event-stream; charset=utf-8",
"Cache-Control": "no-cache, no-transform",
"Transfer-Encoding": "chunked",
Connection: "keep-alive"
});
app.on("message", data => {
res.write(`data: ${JSON.stringify(data)}\n\n`);
});
});
app.post("/api/update", (req, res, next) => {
const message = req.body.type;
app.emit("message", {
title: "Update",
message,
timestamp: new Date()
});
});
my client can be approximated by something like this:
import React, {Component} from "react";
class Button extends Component {
source = new EventSource("api/update");
messageHandler = event => {
console.log(event.data);
};
componentDidMount = () => {
this.source.onmessage = this.messageHandler;
};
render = () => (
<button
onClick={() => {
fetch("/api/update", {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json"
},
body: JSON.stringify({type: "button"})
});
}}
/>
);
}
export default Button;