我似乎无法在express和socket io之间共享会话。它在localhost上有效,而在我的服务器上则无效。我缺少一些东西。
我存储在socket.handshake.session中的数据(此处为“ age”)未保存在快速端。
我的app.js像这样:
var cookieParser = require('cookie-parser');
var session = require('express-session');
var app = express();
app.use(cookieParser()); // read cookies (needed for auth)
var sessionMiddleware = session({
secret: 'keyboard cat',
resave: true,
name: 'sessionId',
saveUninitialized: true,
cookie: { maxAge: 60000 },
// store: new redisStore({ host: 'localhost', port: 6379, client: redisClient, ttl: 86400 }),
});
app.use(sessionMiddleware);
app.set("sessionMW", sessionMiddleware);
module.exports = app;
我的bin \ www像这样:
var app = require('../app');
var debug = require('debug')('testserver:server');
var http = require('http');
var sharedsession = require("express-socket.io-session");
var port = normalizePort(process.env.PORT || '3000');
app.set('port', port);
var server = http.createServer(app);
var io = require('socket.io').listen(server);
var session = app.get("sessionMW")
io.use(sharedsession(session, {autosave:true}));
server.listen(port);
然后我有一个serverEvent.js,它像这样:
var serverEvents = module.exports = function(io){
io.sockets.on('connection', function (socket) {
...
...
...
socket.on('updateAgeSession', function (message) {
socket.handshake.session.age = "18";
socket.handshake.session.save();
console.log(socket.handshake.session);
})
})
}
最后我的路线上有这个index.js:
module.exports = function (app, passport) {
// show the home page (will also have our login links)
app.get('/', function (req, res, next) {
res.cookie('mycookies', 'express');
res.cookie('age', req.session.age);
cookie1= req.cookies;
console.log(req.session);
console.log(req.sessionID);
console.log(req.sessionStore.sessions);
if (req.session.views) {
req.session.views++;
console.log(req.session.views);
} else {
req.session.views = 1
console.log(req.session.views);
}
if(req.session.age){
console.log("OOOOOOOOOOOOOOOOOO");
} else {
console.log("XXXXXXXXXXXXXXXXXXXXXX");
}
res.render('homePage'); // ejs template
});
}
所以我的问题是,当我刷新页面时输入18以上的Im时,req.session.age将是未定义的,但是只有当我的代码在服务器上运行时,它才能在localhost上运行。我不明白。 请帮助
答案 0 :(得分:0)
对于可能遇到与我相同的问题的任何人,这是解决方案:
我还有一个像这样的客户端代码:
var socket = io.connect("http://ip:3000");
var globalVar = [];
// Sent on connection/searchValidatedFromClient by server
socket.on("loadHomePageFromServer", function(message) {
...}
问题是io.connect("http://ip:3000");
。
通过将其更改为io.connect("http://namesite.com");
或io.connect("http://ip:80");
,就可以使用!