获取cookie时未定义的异常

时间:2013-02-20 20:14:13

标签: node.js cookies express

我正在玩节点并且正在尝试在请求上设置cookie但是我得到了一个未定义的异常。这是我的示例应用程序

var express = require('express');

var app = module.exports = express();

process.env.NODE_ENV = 'production';

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

app.get("/", function(req, res){
    res.cookie('cart', 'test', {maxAge: 900000, httpOnly: true});

    res.send("OK");
});

app.get('/users/:id', function(req, res) {
    var s = req.params.id;

    res.send('testcookie: ' + req.cookies.cart);
});    


app.listen(3000);
console.log('Listening on port 3000');

我可以在Charles中确认我正在收到并返回cookie:

enter image description here

但是每当我去/users:id(其中:id显然是某个数字)时的结果我得到一条消息,说明cookies对象是未定义的。

TypeError: Cannot read property 'cart' of undefined
    at c:\Projects\app\app.js:29:42
    at callbacks (c:\Projects\app\node_modules\express\lib\router\index.js:161:37)
    at param (c:\Projects\app\node_modules\express\lib\router\index.js:135:11)
    at param (c:\Projects\app\node_modules\express\lib\router\index.js:132:11)
    at pass (c:\Projects\app\node_modules\express\lib\router\index.js:142:5)
    at Router._dispatch (c:\Projects\app\node_modules\express\lib\router\index.js:170:5)
    at Object.router (c:\Projects\app\node_modules\express\lib\router\index.js:33:10)
    at next (c:\Projects\app\node_modules\express\node_modules\connect\lib\proto.js:199:15)
    at Object.expressInit [as handle] (c:\Projects\app\node_modules\express\lib\middleware.js:31:5)
    at next (c:\Projects\app\node_modules\express\node_modules\connect\lib\proto.js:199:15)

我已经阅读了有关将cookieParser置于其他中间件之上的所有其他SO问题,并且从所有帐户开始,此示例应该可以正常运行,但我对丢失的内容感到茫然。

1 个答案:

答案 0 :(得分:1)

好的,事实证明它与我设置app.configure的方式有关。配置回调函数没有被调用,因为app配置的内部没有调用production ENV的初始化函数,即使我认为它已在上面明确设置。

要解决此问题,我将process.env.NODE_ENV更改为app.settings.env,一切都开始有效。

在此处找到该信息:how to find out the current NODE_ENV the express app is running under?