我试图访问socket.io中的req.user之类的会话对象,以便我可以使用它做一些事情,我使用passport.socket.io
库来执行此操作。但是现在的问题是我不断获得failed connection to socket.io: No session found.
这是代码
var express = require('express');
var session = require('express-session');
var cookieParser = require('cookie-parser');
var MongoStore = require('connect-mongo/es5')(session);
var passport = require('passport');
var passportSocketIo = require("passport.socketio");
var config = require('./config/config');
var sessionStore = new MongoStore({ url: config.database, autoReconnect: true });
var app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.use(cookieParser());
app.use(session({
resave: true,
saveUninitialized: true,
secret: config.secret,
store: sessionStore
}));
app.use(passport.initialize());
app.use(passport.session());
io.use(passportSocketIo.authorize({
cookieParser: cookieParser,
key: express.sid, // Not really sure how to get this key?
secret: config.secret,
store: sessionStore,
success: onAuthorizeSuccess,
fail: onAuthorizeFail,
}));
function onAuthorizeSuccess(data, accept){
console.log('successful connection to socket.io');
accept(null, true);
}
function onAuthorizeFail(data, message, error, accept){
if(error)
throw new Error(message);
console.log('failed connection to socket.io:', message);
accept(null, false);
if(error)
accept(new Error(message));
}
io.connect('connection', function(socket) {
console.log("Something Here");
});
http.listen(3000);
它一直在运行此功能,因为护照无法与socket.io onAuthorizeFail
进行握手。我该如何解决这个问题?
答案 0 :(得分:0)
在我浏览了express-session
文档后,问题就出现了问题。
我已通过更改
解决了问题express.sid => 'connect.sid'
io.use(passportSocketIo.authorize({
key: 'connect.sid'
}));
默认情况下,如表示提供' connect.sid'。