req.session在Express.js中未定义

时间:2013-10-26 15:21:38

标签: javascript node.js express

我看过几篇与此相关的帖子,但没有一个解决了我的问题。

我在server.js中有这段代码

var express = require('express');
var app = express();
app.configure(function(){
    app.set(express.cookieParser());
        app.set(express.session({secret: "This is a secret"}));
});
app.get('/name/:name', function(req, res){
    req.session.name = req.params.name;
    res.send("<a href='/name'>GO</a>");
});
app.get('/name', function(req, res){
    res.send(req.session.name);
});
app.listen(3000);

当我去http://localhost:3000/user/someone那是我得到的输出 TypeError: Cannot set property 'name' of undefined at /Users/Me/Node/server.js:10:19 at callbacks

1 个答案:

答案 0 :(得分:3)

决定从评论中复制。尝试替换

app.configure(function(){
    app.set(express.cookieParser());
        app.set(express.session({secret: "This is a secret"}));
});

app.use(express.cookieParser());
app.use(express.session({secret: "This is a secret"}));

看看会发生什么。