express cookie return undefined

左心房为你撑大大i 提交于 2020-01-13 03:11:08

问题


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



来源:https://stackoverflow.com/questions/12197053/express-cookie-return-undefined

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!