【问题标题】:Socket.io in express js : Router.use requires middleware function but got undefinedexpress js 中的 Socket.io:Router.use 需要中间件功能但未定义
【发布时间】:2017-09-14 12:10:13
【问题描述】:

我正在尝试在我的 express js 应用程序中集成 socket.io(由 express 生成器创建)。

Here is the answer i've followed

但是没有用。

在bin/www中添加了关注

app.io = require('socket.io')();
app.io.attach(server);

当我用app.use('/', require('./routes/index')(app.io)) 修改app.use('/', index); 时;在 app.js 文件中出现以下错误

*

Router.use 需要中间件功能但未定义

*

【问题讨论】:

    标签: javascript node.js sockets express


    【解决方案1】:

    以下是使用 express 实现 socket.io 的方法。

    var express = require('express')
    var app = express();
    var http = require('http').Server(app);
    var io = require('socket.io')(http);
    
    //serve static files and index.html
    app.use(express.static(__dirname + '/'));
    app.get('/', function(req, res){ res.sendFile(__dirname + '/index.html'); });
    
    io.on('connection', function(socket){
        //logic handled in here
    });
    
    http.listen(7000,function(){ console.log('listening on port: 7000'); });
    

    上面的代码有一个路由来处理 index.html 的服务,但是你当然可以像在任何其他应用程序中一样使用其他路由进行扩展。

    以下是在 express 生成器中的路由中访问 socket.io 的方法。

    在 www:

    var server = http.createServer(app);
    var io = require('socket.io')(server);
    module.exports = {io:io}
    

    在 index.js 中

    router.get('/', function(req, res, next) {
      var io = require('../bin/www')
      console.log('I now have access to io', io)
      res.render('index', { title: 'Express' });
    });
    

    请注意,上面的示例纯粹是向您展示如何访问 index.js 中的 io 对象。有许多更好的方法来要求 socket.io 并传递 io 对象,但这些决定似乎超出了这个问题的范围。

    【讨论】:

    • 我在哪里可以添加这个??
    • 我想在 routes/index.js 中使用 io 对象,但根据 yr 代码,一切都在 app.js 文件中完成
    • 您可以在 project_root/bin/www 中进行这些更改。
    • 但是我如何在index.js 中使用io 呢?
    猜你喜欢
    • 2015-04-17
    • 1970-01-01
    • 2018-09-27
    • 1970-01-01
    • 2019-12-22
    • 1970-01-01
    • 1970-01-01
    • 2015-07-08
    • 2015-01-20
    相关资源
    最近更新 更多