Connect + SessionSocket.io + Passport:无法按键查找会话

时间:2013-04-16 09:57:44

标签: node.js sockets session socket.io

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

情况就像this one

我的服务器端代码是:

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 ,如果有人可以添加它,将不胜感激,谢谢

1 个答案:

答案 0 :(得分: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);
});