mattc19
mattc19

Reputation: 718

Sending socket message when post request is received

I would like to emit a socket.io message to all connected clients when any client sends a post request. How can I keep the socket open so that my http request methods can access the connected socket.

I was able to get the following to work but if a client is not connected, the post method doesn't work.

io.on('connection', function(socket){
   console.log('socket connected');
   app.post('/api/guests', function(req, res){
       socket.emit('newguest', {hello: 'world'});
   });
})

I also tried saving the socket to a higher scope and even a global but that didn't seem to work either.

Thanks in advance!

Upvotes: 1

Views: 1387

Answers (1)

marco.marinangeli
marco.marinangeli

Reputation: 901

You don't have to call the "socket emit" inside the on.("connection"...)

Try something like this:

app.post('/api/news', user.can('access private page'), function(req, res, next) {
    io.sockets.emit("nuova:news", data);
});

In my case i pass the "io" variable from the "server.js" file (or app.js) like this:

require('./app/myRoute')(app, user, io);

And receive it in the controller like this:

module.exports = function(app, user, io) {
   ...
}

"io" is declared like this:

var wsServer = require('http').createServer(app);
var io = require('socket.io').listen(wsServer);

I hope these additional info can be useful to you...

Upvotes: 3

Related Questions