我决定在我的应用程序中使用socket.io并偶然发现了一个问题。我使用cookie-session
进行明确授权:
var session = require('cookie-session');
var app = express();
// ...
app.use(session({
keys: ['secretkey1', 'secretkey2']
}))
// ...
app.get('/settings', function(req, res) {
res.type("html");
if (!req.session.sid) {
console.log("NO SID");
req.session.sid = util.randomString();
}
else {
console.log("sid:" + req.session.sid);
}
// doing stuff with req.session.sid
var jadeView = { /*...*/ };
res.status(200).send(mainJade(jadeView));
});
现在我使用socket.io。我想出了如何访问cookie:
io.sockets.on('connection', function(socket) {
var cookie_string = socket.request.headers.cookie;
console.log("cookies: " + cookie_string);
// ...
}
但是如何将cookie_string
转换为会话对象,例如req.session
?
答案 0 :(得分:2)
@ rmflow在2014年的答案似乎不适用于socket.io-client 2.0.2和cookie-session 2.0.0
显然,cookies包(cookie-session的主要依赖关系)需要稍微不同的请求和响应对象。也就是说,请求对象应该具有带有布尔connection
属性的encrypted
对象;此外,响应对象应该具有getHeader
和setHeader
方法。
const session = require('cookie-session')({
name: 'some-session-name',
secret: 'some-session-secret', // or an array of keys as usual
... // Other relevant options
});
io.on('connection', socket => {
let cookieString = socket.request.headers.cookie;
let req = {connection: {encrypted: false}, headers: {cookie: cookieString}}
let res = {getHeader: () =>{}, setHeader: () => {}};
//
session(req, res, () => {
console.log(req.session); // Do something with req.session
})
})
答案 1 :(得分:0)
弄清楚自己:
var req = { headers : {cookie : cookie_string} }
session({ keys: ['secretkey1', 'secretkey2'] })(req, {}, function(){})
console.log(req.session.sid);