Express中的会话无效

时间:2011-11-10 10:47:52

标签: node.js express connect

我正在尝试使用Express中的会话。我尽可能仔细地阅读了文档但是在我的代码和示例之间找不到任何差异 - 但是,会话似乎没有初始化。

这是我app.js的开头

var express = require('express')
  , routes = require('./routes')
  , customRoutes = require('./routes/custom.js');

var app = module.exports = express.createServer();

// Configuration

app.configure(function(){
  app.set('views', __dirname + '/views');
  app.set('view engine', 'jade');
  app.use(express.bodyParser());
  app.use(express.methodOverride());
  app.use(app.router);
  app.use(express.static(__dirname + '/public'));

  app.use(express.cookieParser());  
  app.use(express.session({ secret: "keyboard cat" }));

});

app.configure('development', function(){
  app.use(express.errorHandler({ dumpExceptions: true, showStack: true })); 
});

app.configure('production', function(){
  app.use(express.errorHandler()); 
});

// Routes

app.get('/', function(req, res){

    req.session.something = "please?";
    req.session.boo = true;
    req.session.int = 100;

    console.log(req.session); // undefined
});

当我运行它时:TypeError:无法设置未定义的属性'something'。

要检查什么?

$ npm ls

ââ⬠cradle@0.5.7
â âââ vargs@0.1.0
â ââ⬠vows@0.5.13
â   âââ eyes@0.1.6
ââ⬠express@2.5.0
â âââ connect@1.7.2
â âââ mime@1.2.4
â âââ mkdirp@0.0.7
â âââ qs@0.3.2
âââ node-static@0.5.9

1 个答案:

答案 0 :(得分:5)

您没有指定任何会话商店,请查看此处的示例:https://github.com/alessioalex/Nodetuts/blob/master/express_samples/app.js#L15-31

例如,指定内存存储(这仅适用于开发):

var MemStore = express.session.MemoryStore;
...
app.use(express.session({secret: 'secret_key', store: MemStore({
  reapInterval: 60000 * 10
})}));