6

我正在尝试在 express.js 上设置 cookie,但它返回未定义。我搜索了很多网页并放在express.cookieParser()上面,app.use(app.router) 但它仍然无法返回正确的值。

应用程序.js

app.configure(function(){
   var RedisStore = require('connect-redis')(express);
    app.use(express.logger());
    app.set('view options', { layout: false });
    app.set('views', __dirname + '/views');
    app.set('view engine', 'jade');
    app.use(express.bodyParser({uploadDir: './uploads/tmp'}));
    app.use(express.methodOverride());
    app.use(express.cookieParser());
    app.use(express.session({ secret: "william", store: new RedisStore }));
//Initialize Passport!  Also use passport.session() middleware, to support
//persistent login sessions (recommended).
    app.use(passport.initialize());
    app.use(passport.session());
    //app.router should be after passportjs
    app.use(app.router);
    app.use(express.compiler({ src: __dirname + '/public', enable: ['less']}));
    app.use(express.static(path.join(__dirname, 'public')));
});

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

app.get('/test', function(req, res) {
    res.send('testcookie: ' + req.cookies.cart);
});

结果:

testcookie: undefined
4

3 回答 3

4

Cookies are set in HTTP Headers. res.cookie() just sets the header for your HTTP result, but doesn't actually send any HTTP. If your code was syntactically correct and it ran, it would actually just sit and not return anything. I also fixed some syntax bugs in your code in this app.get():

app.get('/', function(req, res) {
    res.cookie('cart', 'test', {maxAge: 900000, httpOnly: true});
    res.send('Check your cookies. One should be in there now');
});
于 2012-08-30T21:09:38.377 回答
2

res.end()在设置 cookie 之后,您需要发送一些东西,或者至少调用。否则res.cookie(),所做的只是将一些标头添加到稍后将发送出去的标头列表中。

于 2012-08-30T16:57:43.830 回答
0

将 cookie 名称设置为 value,其中可能是转换为 JSON 的字符串或对象。路径选项默认为“/”。

res.cookie('name', 'tobi', { domain: '.example.com', path: '/admin', secure: true });

这是链接以获取更多详细信息

http://expressjs.com/api.html#res.cookie

于 2013-08-21T08:50:59.867 回答