How to use socket.io in express routes?

前端 未结 2 1855
说谎
说谎 2020-12-02 13:31

I\'m using Express with Socket.io but I can\'t figure out how to use SocKet.io in Express routes.

I end up doing this in \"app.js\"

...
...

// devel         


        
相关标签:
2条回答
  • 2020-12-02 14:06

    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!"});    
      })
    };
    
    0 讨论(0)
  • 2020-12-02 14:16

    You can use simple middleware before routes, and then use in res object

    app.use((req, res, next) => {
      res.io = io
      next()
    })
    
    0 讨论(0)
提交回复
热议问题