Express cookie return undefined

I am trying to set a cookie on express.js, but it returns undefined. I searched a lot of web pages and placed express.cookieParser()above app.use(app.router) but it still cannot return the correct 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);
});

result:

testcookie: undefined
+5
source share
3 answers

Cookies are set in HTTP headers. res.cookie()just sets the header for your HTTP result, but doesn't actually send HTTP. If your code was syntactically correct and it worked, it actually just sat there and returned nothing. I also fixed some syntax errors 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');
});
+3
source

- res.end() cookie. res.cookie() , .

+1

Set the cookie name for the value where the string or object converted to JSON can be. The default path parameter is "/".

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

Here is the link for more details.

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

0
source

All Articles