我在使用我的应用程序时收到错误“TypeError: Cannot read property 'handshaken' of undefined”,因为我已经安装了 socket.io
似乎文件中的checkUserHaveConnect方法helpers/utils.js
导致了错误,因为我的 console.log("io 2", io") 在错误之前被调用(这可以在下面的屏幕截图中看到)
奇怪的是,这个错误不会发生在我的开发环境(笔记本电脑)上,而只会发生在生产环境中(nodejitsu)。
首先,这是我启动 socket.io 连接的索引文件。
index.js
var server = http.createServer(app);
var io = require('socket.io').listen(server);
GLOBAL.io = io;
// launch
server.listen(port);
//With Socket.io >= 1.0
io.use(passportSocketIo.authorize({
cookieParser: express.cookieParser,
key: EXPRESS_SID_KEY, // the name of the cookie where express/connect stores its session_id
secret: SESSION_SECRET, // the session_secret to parse the cookie
store: sessionStore, // we NEED to use a sessionstore. no memorystore please
success: onAuthorizeSuccess, // *optional* callback on success - read more below
fail: onAuthorizeFail, // *optional* callback on fail/error - read more below
}));
io.on('connection', function (socket) {
console.log("connection come");
socket.on('disconnect', function (socket) {
console.log("disconnect come");
});
});
function onAuthorizeSuccess(data, accept){
console.log('successful connection to socket.io');
accept(null, true);
}
function onAuthorizeFail(data, message, error, accept){
console.log('failed connection to socket.io:', message);
if(error){
throw new Error(message);
}
// We use this callback to log all of our failed connections.
accept(null, false);
}
console.log('The magic happens on port' + port);
以下是可能导致问题的方法。
助手/utils.js
var passportSocketIo = require("passport.socketio");
exports.emitData = function(userId, eventName,data){
console.log("io 1", io);
var sockets = passportSocketIo.filterSocketsByUser(io, function(user){
if(user._id){
return user._id.toHexString() === userId.toHexString();
}
return false;
});
sockets.forEach(function(socket){
socket.emit(eventName,data);
});
return sockets.length;
}
exports.checkUserHaveConnect = function(userId){
console.log("io 2", io);
return passportSocketIo.filterSocketsByUser(io, function(user){
if(user._id){
return user._id.toHexString() === userId.toHexString();
}
return false;
}).length;
}