我遵循了有关如何使用 cookie 解析和 MemoryStore 作为会话存储创建节点快速应用程序的教程。但是在安装了某些模块的最新版本后,我的应用程序不再工作了。昨天我安装了最新版本的“express”、“connect”和“cookie”,现在我无法再将会话从 MemoryStore 中取出。
下面是我为重现问题而设置的简单应用程序:
server.js -----------
var express = require('express');
var MemoryStore = express.session.MemoryStore;
var sessionStore = new MemoryStore();
var connect = require('connect');
var Session = connect.middleware.session.Session;
var cookie = require('cookie');
module.exports.startServer = function() {
var app = express();
// Configuration
app.configure(function() {
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.cookieParser());
app.use(express.session({
store : sessionStore,
secret : 'secret',
key : 'express.sid'
}));
app.use(express.static(__dirname + '/public'));
app.use(app.router);
});
app.configure('development', function() {
app.use(express.errorHandler({
dumpExceptions : true,
showStack : true
}));
});
app.configure('production', function() {
app.use(express.errorHandler());
});
// Init routes
app.post('/login', function(req, res){
var credentials = req.body;
if (!(credentials.username && credentials.password)){
res.redirect('/login.html');
return;
}
if (credentials.username === 'user1' && credentials.password === 'pass1'){
req.session.user = credentials.username;
req.session.clientId = credentials.clientId;
res.redirect('/post-message.html');
}else{
req.session.destroy();
res.redirect('/login.html');
}
});
app.post('/postMsg', authenticate, function(req, res){
res.send('posted');
});
app.listen(4000);
function authenticate(req, res, next) {
// check if there's a cookie header
if (req.headers.cookie) {
// if there is, parse the cookie
req.cookie = cookie.parse(req.headers.cookie);
req.sessionID= req.cookie['express.sid'];
// note that you will need to use the same key to grad the
// session id, as you specified in the Express setup.
sessionStore.get(req.sessionID, function(err, session) {
if (session && session.user) {
// save the session data and accept the connection
req.session = new Session(req, session);
next();
}
else {
//Turn down the connection
res.redirect('/login.html');
}
});
} else {
// if there isn't, turn down the connection with a message
// and leave the function.
res.redirect('/login.html');
}
}
};
我可以在调试器中看到一切似乎都工作正常,直到我尝试通过调用“/postMsg”路由来发布消息。然后它进入“authenticate”函数并尝试从 sessionStore 中获取带有“req.sessionID”的会话。这不再成功,并且 sessionStore.get 为会话返回 undefined 。但是,如果我使用调试器查看 sessionStore,我可以看到存储中有一个会话,并且它似乎也与 sessionID 匹配。
有谁知道我的脚本有什么问题?
感谢帮助!