gpt4 book ai didi

node.js - Passport.socketio 一直说 - 连接到 socket.io : No session found 失败

转载 作者:太空宇宙 更新时间:2023-11-04 02:17:41 24 4
gpt4 key购买 nike

我正在尝试访问像socket.io中的req.user这样的 session 对象,以便我可以用它做一些事情,我使用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);

它一直运行这个函数,因为 Passport 未能与 socket.io onAuthorizeFail 握手。我该如何解决这个问题?

最佳答案

在我浏览完 express-session 文档后,发现是 key 问题。

我已经通过更改解决了该问题

express.sid => 'connect.sid'

io.use(passportSocketIo.authorize({
key: 'connect.sid'
}));

似乎 Express 默认情况下会提供“connect.sid”。

关于node.js - Passport.socketio 一直说 - 连接到 socket.io : No session found 失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34963874/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com