【问题标题】:how to access http.Server.connection property in express 3 router?如何访问 express 3 路由器中的 http.Server.connection 属性?
【发布时间】:2012-11-06 19:09:18
【问题描述】:

我想在我的 express 3 路由中使用 http.Server.connections? 有没有办法得到它了?

我应该只是 app.set('server', server);

express.createServer() 已弃用,express 应用程序不再从 http.Server 继承

var app = express(),
server = http.createServer(app);
server.listen(8080);
...
module.exports = function (app) {

    app.get('/connections', function (req, res) {
        res.send({
            connections: app.connections 
            // app != http.Server in express 3
        });
    });

};

【问题讨论】:

    标签: node.js express connect


    【解决方案1】:

    您需要发送server.connections,而不是app.connections,因为您使用过:

    server = http.createServer(app);

    所以你的代码变成了:

    app.get('/connections', function (req, res) {
        res.send({
            connections: server.connections 
        });
    });
    

    【讨论】:

    • 这里需要注意的是,app.listen() 不会返回一个正常的http服务器,因此您必须手动创建一个服务器才能访问服务器方法
    【解决方案2】:
    app.locals.connections = app.connections
    

    然后在您的回复中:

    res.send({ connections: res.locals.connections});
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-14
      • 1970-01-01
      • 2014-10-12
      • 1970-01-01
      • 2016-02-19
      • 1970-01-01
      相关资源
      最近更新 更多