node.js 如何在快速路由中使用 socket.io?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20909778/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 16:35:16  来源:igfitidea点击:

How to use socket.io in express routes?

node.jsexpresssocket.io

提问by André

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

我正在将 Express 与 Socket.io 一起使用,但我不知道如何在 Express 路由中使用 Socket.io。

I end up doing this in "app.js"

我最终在“app.js”中执行此操作

...
...

// development only
if ('development' == app.get('env')) {
  app.use(express.errorHandler());

}

var server = http.createServer(app);
var io = require("socket.io").listen(server);


app.get('/', routes.index);
app.get('/users', user.list);
app.post('/cmp', function(request, response) {
    var client = new pg.Client("pg://user:[email protected]/db_name");
    client.connect(function(err) {

      // Get the product_id and bid
      var product_id = request.body.product_id;
      var bid = request.body.bid.split('b')[1];         

      // If not get the connection
      if(err) {
        return console.error('could not connect to postgres', err);
      }


      client.query('select 1 from product_bid where product_id =  and number_bid = ', [product_id, bid], function(err, result) {
        if(err) {
          return console.error('error running query', err);
        }

        if (result.rowCount == 1) {
          // do not insert          

        } else {
          // insert
          // Insert to the DB
          client.query('insert into product_bid (product_id, number_bid) values (, )', [product_id, bid], function(err, result) {
            if(err) {
              return console.error('error running query', err);
            }

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

          });
        }

      });
    });
});


server.listen(app.get('port'), function(){
  console.log('Express server listening on port ' + app.get('port'));
});



// ---------------
io.on('connection', function(socket){
    console.log("alguem se ligou!");
    socket.emit('event_from_server', {message: 'conectou-se ao servidor'});
});

How can I define the route to "/cmp" like this and passing the var "io" inside?

我怎样才能像这样定义到“/cmp”的路由并在里面传递var“io”?

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

So that in "/routes/cmp.js" I can do something like this:

所以在“/routes/cmp.js”中我可以做这样的事情:

exports.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!"});    
};

Some clues?

一些线索?

回答by Michelle Tilley

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 routesas

然后定义routes

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!"});    
  })
};

回答by Oleg Protsenko

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

您可以在路由之前使用简单的中间件,然后在 res 对象中使用

app.use((req, res, next) => {
  res.io = io
  next()
})