5

我在我的应用程序中使用connect,passportsession.socket.io模块。在connectionsession.socket.io 的事件中,我收到一个错误:could not look up session by key: connect.sid

情况是这样

我的服务器端代码是:

var mod_http            = require('http');
var mod_connect         = require('../../lib/node_modules/connect');
var mod_connectRoute    = require('../../lib/node_modules/connect-route');
var mod_ejs             = require('../../lib/node_modules/ejs');
var mod_SessionSockets  = require('../../lib/node_modules/session.socket.io');
var mod_passport        = require('../../lib/node_modules/passport'), LocalStrategy = require('../../lib/node_modules/passport-local').Strategy;
var mod_fs              = require('fs');

var app = mod_connect();
var cookieParser = mod_connect.cookieParser('your secret sauce'),
sessionStore = new mod_connect.middleware.session.MemoryStore();

app.use(mod_connect.static(folder));
// Configure the app connection
app.use(cookieParser);
app.use(mod_connect.bodyParser());
app.use(mod_connect.session({ secret: 'logged' }));
app.use(mod_passport.initialize());
app.use(mod_passport.session());

app.use(mod_connectRoute(function (router) {
    router.get('/', function (req, res, next) { 
        ...
    }
}

var server  = mod_http.createServer(app), 
    io = require('../../lib/node_modules/socket.io').listen(server);
// Limit the messages shown.
io.set('log level', 2);
// Create a session.
var sessionSockets = new mod_SessionSockets(io, sessionStore, cookieParser);

// Fire when a browser install a connection. A page refresh closes the connection and creates new one.
sessionSockets.on('connection', function (err, socket, session) {
    console.log(err);
    console.log(sessionStore);
    console.log('Hello!');
}); 
server.listen(4000);

客户端代码:

<!DOCTYPE html> <!-- HTML 5 -->
<html>
    <head>
        <link rel="stylesheet" type="text/css" href="/style.css">
        <script src="/jquery-1.9.1.js"></script>
        <meta charset="utf-8">
        <title> Test </title>
    </head>
    <body>  
        <script src="/socket.io/socket.io.js"></script>
        <script type="text/javascript">
            socket = io.connect('http://'+location.host);
        </script>
        <script src="/functions.js"></script>
        ...
    </body>
</html>

当我打开localhost:4000页面时,我可以在 node.js 控制台上看到以下输出:

[Error: could not look up session by key: connect.sid]
{ sessions: {} }
Hello!

PS:由于我的声誉较低,我无法为讨论添加新标签,但我认为此讨论将需要标签session.socket.io,如果有人可以添加它,将不胜感激,谢谢

4

1 回答 1

0

解决这个问题的一个简单方法是使用passport-socketio

下面的代码应该可以工作:

var passportSocketIo = require("passport.socketio");
io.use(passportSocketIo.authorize({
  cookieParser: cookieParser,
  secret:      'your secret sauce',
  store:       sessionStore,
  success:     onAuthorizeSuccess,
  fail:        onAuthorizeFail,
}));


io.sockets.on('connection', function(socket) {
  console.log(socket.request.sid);
});
于 2014-10-05T01:47:20.250 回答