NodeJS - Framework for stateless sessions?

白昼怎懂夜的黑 提交于 2019-12-05 21:15:12
Robert Christian

There is express middleware which supports this:

https://github.com/expressjs/cookie-session

cookieSession()

Provides cookie-based sessions, and populates req.session. This middleware takes the following options:

  • name - cookie name defaulting to "session"
  • keys - list of secret keys to prevent tampering
  • secret - used as single key if keys are not specified
  • options - additional options such as secure, httpOnly, maxAge, etc.

Middleware:

var cookieSession = require('cookie-session')
...
app.use(cookieSession({
    name: "my_session_cookie",
    secret: "dont_tell_anybody_the_secret_and_change_it_often",
    options: { ... }
));

app.use((req, res, next) => {
    // set options on req.session before your response goes out
    req.session.viewCount = (req.session.viewCount || 0) + 1;
    res.end(`You viewed the page ${req.session.viewCount} times.`);
});

To clear a cookie simply assign the session to null before responding:

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