How to use socket.io in express routes?

How about a higher order function?

exports.cmp = function(io) {
  return function(req, res){
    var product_id = req.body.product_id;
    var bid = req.body.bid.split('b')[1];       

    io.sockets.emit("bidSuccess", {product_id: product_id, bid: bid});
    response.json(200, {message: "Message received!"});    
  }
};

and then

app.post('/cmp', routes.cmp(io));

As another option, I’ll sometimes format my routes in the following format:

var routes = require('./routes/routes');

routes(app, io);

And then define routes as

module.exports = function(app, io) {
  app.post('/cmp', function(req, res){
    var product_id = req.body.product_id;
    var bid = req.body.bid.split('b')[1];       

    io.sockets.emit("bidSuccess", {product_id: product_id, bid: bid});
    response.json(200, {message: "Message received!"});    
  })
};

Leave a Comment