node.js 更改 Express 中的 cookie 过期时间

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14049294/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 16:50:29  来源:igfitidea点击:

Change cookie expiration in Express

node.jssessioncookiesexpressconnect

提问by user1161657

Because I didn't define a maxAge when calling expressServer.use(express.session({params}))the cookie's expiration is set as "Session".

因为我在调用expressServer.use(express.session({params}))cookie 的过期时间设置为“Session”时没有定义 maxAge 。

I would like to add a "remember me" feature when logging in. If "remember me" is selected, the expiration will be extended to a month.

我想在登录时添加“记住我”功能。如果选择“记住我”,有效期将延长至一个月。

How would I go about doing this? I tried simply extending the maxAge, but that didn't seem to do anything...

我该怎么做呢?我尝试简单地扩展 maxAge,但这似乎没有任何作用......

expressServer.get '/blah', (request, response) =>
    request.session.cookie.maxAge = 2592000
    response.end 'hello there'

Thanks for the help!

谢谢您的帮助!

** EDIT**

**编辑**

I tried making a simple server to test updating a user's cookie. I'm using Express 3.0.4

我尝试制作一个简单的服务器来测试更新用户的 cookie。我正在使用 Express 3.0.4

When I visit 127.0.0.1:9000/blah, the browser cookie's "expires" field is still "session"...

当我访问 127.0.0.1:9000/blah 时,浏览器 cookie 的“过期”字段仍然是“会话”...

express = require 'express'

expressServer = express()
expressServer.use express.cookieParser()
expressServer.use express.session
    secret: 'supersecret'
    cookie:
        path: '/'
        httpOnly: true

expressServer.get '/', (request, response) =>
    response.end 'hello'

expressServer.get '/blah', (request, response) =>
    request.session.cookie.maxAge = 3600000
    response.end 'hello again'

expressServer.listen 9000
console.log 'server running'

Grrrrrrr....

咕噜噜....

回答by chovy

I have a checkbox that says "remember me" on the /login page:

我在 /login 页面上有一个复选框,上面写着“记住我”:

<p class="remember">
  <input type="checkbox" id="remember" name="remember" value="1" />
  <label for="remember">Remember me</label>
</p>

Then in my POST route to /login I do some sanity checking and set the session if req.body.rememberis set otherwise its just a window session:

然后在我到 /login 的 POST 路由中,我进行了一些完整性检查并设置了会话,req.body.remember否则它只是一个窗口会话:

  //user is authenticated
  //set session length
  if ( req.body.remember ) {
    var hour = 3600000;
    req.session.cookie.maxAge = 14 * 24 * hour; //2 weeks
  } else {
    req.session.cookie.expires = false;
  }

  req.session.userid = user._id;

Add the following few lines (I use redis) in app.js:

在 app.js 中添加以下几行(我使用 redis):

  app.use(express.cookieParser('secret-word'));
  app.use(express.session({
    store: new RedisStore({
      host: cfg.redis.host,
      db: cfg.redis.db
    }),
    secret: 'another-secret'
  }));

回答by borisdiakur

If you want to implement rolling sessions with cookie-sessionsin express 4, configure the middleware like this:

如果要在 express 4 中使用cookie-sessions实现滚动会话,请像这样配置中间件:

app.use(cookieSession({
    secret: your_secret,
    maxAge: your_maxAge,
    key: 'sessionId'
}));

Note that you do not need to set the expiresoption.

请注意,您不需要设置该expires选项。

In order to extend your session, simply alter it like this:

为了延长您的会话,只需像这样更改它:

app.get('*', function (req, res, next) {
    req.session.foobar = Date.now();
    next();
}

Note that in express 4 there is no req.session.touch().

请注意,在 express 4 中没有req.session.touch().

回答by AmirtharajCVijay

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

将 cookie 名称设置为 value,其中可以是字符串或转换为 JSON 的对象。路径选项默认为"/".

res.cookie('rememberme', '1', 
                { expires: new Date(Date.now() + 900000), httpOnly: true });

For further references following the link may be used

如需进一步参考,可以使用以下链接

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

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

回答by Hitchcott

I found an answerthat seems to work for me; add it to the top of your routes.

我找到了一个似乎对我有用的答案;将其添加到路线的顶部。

app.all '*', (req,res,next) ->
  if req.method is 'HEAD' or req.method is 'OPTIONS'  
    next()
  else
    req.session._garbage = Date();
    req.session.touch();
    next();

回答by sumitjainjr

Or You can try this, it worked for me:

或者你可以试试这个,它对我有用:

if ( req.body.remember ) 
{
    var oneWeek = 7 * 24 * 3600 * 1000; //1 weeks                    
    req.session.cookie.expires = new Date(Date.now() + oneWeek);
    req.session.cookie.maxAge = oneWeek; 
}