Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

express cookie return undefined

I'm trying to set cookie on express.js but it return undefined. I've searched many web pages and put express.cookieParser() above app.use(app.router) but it still can't return the right value.

app.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);
});

the result:

testcookie: undefined
like image 895
LiJung Avatar asked Aug 30 '12 12:08

LiJung


2 Answers

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');
});
like image 143
EhevuTov Avatar answered Sep 25 '22 21:09

EhevuTov


You need to send something out, or at least call res.end(), after setting the cookie. Otherwise all res.cookie() does is add some headers to a list of headers that will be sent out later.

like image 26
ebohlman Avatar answered Sep 23 '22 21:09

ebohlman