express cookie return undefined

2019-04-08 22:37发布

问题:

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

回答1:

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');
});


回答2:

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.



回答3:

Set cookie name to value, where which may be a string or object converted to JSON. The path option defaults to "/".

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

Here is the Link for more detail

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