我正在玩节点,并试图在请求上设置一个 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:
但是每当我去的结果/users:id
(其中 :id 显然是某个数字)时,我都会收到一条消息,说 cookie 对象未定义。
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 问题,并且从所有方面来看,这个示例应该可以工作,但我不知道缺少什么。