How to emit a socket.io response within post request in NodeJS
Asked Answered
D

2

5

I have a node server running a react application, integrated with Socket.io. All works fine. I also have an external application that uses the same data. What I want to do is, when the data changes, post to my node server and then in the response, emit to any data to users who are currently subscribed to the socket.

//SERVER CODE LIVES ABOVE HERE...

const io = require('socket.io')(server);

io.on('connection', (socket) => {
  socket.on('create data', function(data) {
    //a place to create data, once complete triggers everyone subscribed to get an update.
    socket.emit('data created', data);
  });

});


app.post('/api/datacreated/', function(req, res) {
  //HOW DO I EMIT IN HERE?! - this is coming from an external resource
  socket.emit('data created', data);
})

Cheers for any time you've got!

Degroot answered 27/6, 2017 at 9:12 Comment(0)
E
6

Socket is locally scoped. io.sockets is not, so you can do:

app.post('/api/datacreated/', function(req, res) {
 //this is coming from an external resource
 io.sockets.emit('data created', data);
})
Empoverish answered 27/6, 2017 at 9:19 Comment(3)
There's something so satisfying about linking apps together. Perfect, thanks!Degroot
@Jonasw you just made my dayMotorway
@Motorway glad to help ;)Empoverish
C
0

the solution that was working for me

const io = new Server(...)
global.io = io

app.post('/api/datacreated/', function(req, res) {
 global.io.emit('data created', data);
})
Costrel answered 27/2 at 14:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.