来自我的server.js
:
var app = require('express')();
var server = require('http').createServer(app);
var io = require("socket.io").listen(server);
server.listen(port,function (){
console.log('Listening is at ' + port);
});
现在我正尝试将app
和io
传递给模块:
require('./routes/moduleX.js')(app,io);
在./routes/moduleX.js
:
module.exports = function(app,io){
app.get('/moduleXX',function(req,res){ /
res.render('moduleXX.ejs');
var dataToBeSent = {
YYYY: 10,
NNNNN: 5,
TTTTT: [2,4,5,6,7],
};
io.sockets.on('connection', function (socket) {
console.log('Client Connected');
socket.emit('subReady', { prep: dataToBeSent });
});
});
}
我收到TypeError: Cannot read property 'sockets' of undefined
我的问题是为什么io
在这里未定义?以及如何正确地做到这一点。
答案 0 :(得分:-1)
更改以下代码
io.sockets.on('connection', function (socket) {
console.log('Client Connected');
socket.emit('subReady', { prep: dataToBeSent });
});
到
io.on('connection', function (socket) {
console.log('Client Connected');
socket.emit('subReady', { prep: dataToBeSent });
});