问题
I'm trying to learn the "cookie-session" module for Node. https://github.com/expressjs/cookie-session
I have a hard time understanding how to pass options for the cookie. For example expiration. Default seems to be a year!
This is the instructions about options for the cookie:
"Other options are passed to cookies.get()
and cookies.set()
allowing you to control security, domain, path, and signing among other settings."
But i dont get it!
Am I supposed to require cookies module as well?
Or do I somehow change the options trough var session = require('cookie-session')
?
I have tried session.cookies.set()
, but that doesnt seems to work.
I have tried to read the sourcecode in the "cookie-session" and "cookies" module for clues, but I dont know what to look for!
回答1:
Short answer
Define the options you want to specify in the creation of the session, as illustrated in the docs: https://github.com/expressjs/cookie-session. They will be used when creating the cookie (including the expires
option).
app.use(session({
keys: ['key1', 'key2'],
secureProxy: true // if you do SSL outside of node
// more options here...
}))
Long answer
Using the example above, when you pass in the configuration object into session
, you are sending this object into the function here. This opts
is passed around, but in particular, stored as req.sessionOptions here. req
is passed in when creating a new Session
, and stored as this._ctx. Finally, when save
is called on the Session
, these options are pulled from the sessionOptions and used in the set call for the cookies:
Session.prototype.save = function(){
var ctx = this._ctx;
var json = this._json || encode(this);
var opts = ctx.sessionOptions;
var name = ctx.sessionKey;
debug('save %s', json);
ctx.sessionCookies.set(name, json, opts);
};
So the options you pass in originally are passed to the set
call when creating the cookie.
来源:https://stackoverflow.com/questions/24065054/how-to-pass-cookie-options-in-cookie-session-1-0-2