简体   繁体   English

nodejs会话cookie浏览器存储

[英]nodejs session cookie browser storage

Server is nodejs with express-session, passport, express 服务器是带有快速会话,通行证,快速的Node.js

I want to avoid saving a cookie when the user is not authenticated , is this possible? 我想避免在用户未通过身份验证保存cookie ,这可能吗?

var sessionStore = new session.MemoryStore;
app.use(session({
    cookie: { maxAge: null,
              httpOnly: true,
              secure: true,
            },
    store: sessionStore,
    resave: 'false',
    secret: 'somthing',
    name: "id",
    saveUninitialized: false
}));

Is it somehow possible to only store the cookie when the user did successfully login? 是否可以仅在用户成功登录后才存储cookie? Thanks! 谢谢!

You have to create an express-session: https://www.npmjs.com/package/express-sessions and then store the session like this: 您必须创建一个快速会话: https : //www.npmjs.com/package/express-sessions ,然后按以下方式存储该会话:

let session = require("express-session");

app.use(session({
    secret: "secret",
    resave: false,
    saveUninitialized: true,
    cookie: {secure: true,
        httpOnly: true,
        maxAge: 1000 * 60 * 60 * 24
    }
}));

This session will be stored during your visit on the webpage. 该会话将在您访问网页期间存储。 If you want to set values to the cookie, simply request the cookie in a request and set somekind of value: 如果要为cookie设置值,只需在请求中请求cookie并设置某种值:

router.route("/login")
    .post(function(req, res) {

        req.session.Auth = req.body.user // => user values?
    })

OR You can use cookie-session( https://www.npmjs.com/package/cookie-session ) 或者您可以使用cookie-session( https://www.npmjs.com/package/cookie-session

If you use cookie session then if you made any changes to session variable or from server side, then no need to restart server. 如果您使用cookie会话,则如果对会话变量或从服务器端进行了任何更改,则无需重新启动服务器。

app.use(cookieSession({
 name: 'session',
 keys: ['key1', 'key2']
}))

app.get('/', function (req, res, next) {
  // Update views 
  req.session.views = (req.session.views || 0) + 1

  // Write response 
  res.end(req.session.views + ' views')
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM