Reputation: 798
I have an express application that opens up a socket connection with my frontend React application.
I want to emit an event to the connected socket whenever someone sends a post request to my server with json data but socket.emit doesn't fire in a.post callback. io.sockets.emit however works fine but is of no use to me in this case.
This fails:
io.on('connection', (socket) => {
app.post('/event', (req, res) => {
socket.emit('someevent', req.body);
res.sendStatus(200);
}
}
But this passes:
io.on('connection', (socket) => {
app.post('/event', (req, res) => {
io.sockets.emit('someevent', req.body);
res.sendStatus(200);
}
}
Upvotes: 2
Views: 993
Reputation: 798
SLaks's comment is correct but it did not help me solve my problem.
What I ended up doing is:
/event
from the client, I added a hidden input field containing the ID of socket connection.Then in my /event
route handler, I did:
app.post('/event', function(req, res) {
io.sockets.in(req.body.socketId).emit('someevent', req.body);
res.sendStatus(200);
});
This works because by default each socket connection joins a room identified with its socket-id and messages can be sent to rooms using the io
object iteself (no need to obtain a socket object from io.on('connection', socket =>{})
Upvotes: 4