express-sse
express-sse copied to clipboard
Client is only recieving events after server restart
This is more of a help request than anything but I'm at my wits end as to whats going wrong here.
When I try to send events to a client they seem to only be received when the server restarts (usually from saving the file and nodemon
restarts the server).
Here is my code:
Server
server.js
const express = require("express");
const stream = require("./routes/api/stream");
const listener = require("./routes/listener");
var app = express();
var port = process.env.PORT || 5000;
app.get('/api/stream/', stream.init);
app.use('/miniserver/', listener);
app.listen(port, () => console.log(`Server listening on port ${port}`));
stream.js
const SSE = require("express-sse");
const stream = new SSE(["Connection established with SSE server"]);
module.exports = stream;
listener.js
const express = require("express");
const stream = require("./api/stream");
const router = express.Router();
router.get("/curr_ing/:ing", (req, res) => {
console.log(req.url, req.params.ing);
stream.send({ name: "curr_ing", data: req.params.ing });
})
module.exports = router;
Client
class App extends Component {
constructor(props) {
super(props)
this.source = new EventSource("/api/stream");
}
componentDidMount() {
this.source.addEventListener('message',
(event) => {
console.log(event.data);
}, false);
}
Logs
Node.js
Server listening on port 5000
/curr_ing/1 1
/curr_ing/2 2
[nodemon] restarting due to changes...
[nodemon] starting `node server.js`
After restarting React.js
"Connection established with SSE server"
{"name":"curr_ing","data":"1"}
{"name":"curr_ing","data":"2"}
I'm facing the same issue. Did you ever figure this out?
Okay two things for this.
One, my node server is behind nginx, so I had to add some nginx directives to enable the sse.
Second, you need to install the compression
package and use app.use(compression)
.