我正在尝试在我的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('/', index);
为 app.use('/', require('./routes/index')(app.io))
;在 app.js 文件中我收到以下错误
*
Router.use requires middleware function but got undefined
*
最佳答案
以下是如何使用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 对象,但这些决定似乎超出了这个问题的范围。
关于javascript - Express js : Router. 中的 Socket.io 使用需要中间件函数但未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43475805/