简体   繁体   English

每个请求都表示更改会话

[英]Express change session every request

I have a function to login我有一个登录功能

app.post('/doLogin', function(req,res){
        db.users.findOne({username: req.body.username}, function(err, user) {
            if( err ) {
                console.log("Login fail");
            } 
            else if (user != null) {
                if (req.body.password == user.password) {
                    req.session.user_role = "user";
                    req.session.save();
            } else {
                req.session.user_role = "null";
                console.log("Wrong login");
            }
        }
        res.send({redirect: "/"});
    });

});

This function is used to save a variable into session req.session.user_role = "user";该函数用于将变量保存到会话中req.session.user_role = "user"; But when the new request to check user logged in or not但是当新的请求检查用户是否登录时

app.get('/', function(req,res){
    redis.get('sess:' + req.session.id, function(err, result){
        console.log("Get session: " + util.inspect(JSON.parse(result),{ showHidden: true, depth: null }));
    });
    if ((req.session.user_role == "user")) {
          console.log("Logged in");
    } else {
        console.log("Logged out");
    }
});

Then return always is "Logged out", because the session is changed.然后返回总是“注销”,因为会话已更改。 I use Redis to store session, I think it is Redis fault because when I stop using Redis, it's OK Please help me!我使用Redis来存储会话,我认为是Redis的故障,因为当我停止使用Redis时,就可以了 请帮帮我!

Express-session uses the cookie to set or get the session id from the client Express-session使用 cookie 来设置或从客户端获取会话 ID

as stated on the documentation文档中所述

Please note that secure: true is a recommended option.请注意,secure: true 是推荐选项。 However, it requires an https-enabled website, ie, HTTPS is necessary for secure cookies.但是,它需要启用 https 的网站,即安全 cookie 需要 HTTPS。 If secure is set, and you access your site over HTTP, the cookie will not be set.如果设置了安全,并且您通过 HTTP 访问您的站点,则不会设置 cookie。

Remember the below points:记住以下几点:

  • If you are not hosting on HTTPS connection cookie secure flag should be set to false.如果您不在 HTTPS 连接上托管,则 cookie 安全标志应设置为 false。

  • If the you are using a proxy thats hosted on the HTTPS you should set trust proxy to 1. Refer the documentation如果您使用的是托管在 HTTPS 上的代理,则应将信任代理设置为 1。请参阅文档


Below option will resolve the issue of session ID reset for every request下面的选项将解决每个请求的会话 ID 重置问题

cookie: { secure: false }

for example:例如:

app.use(session({
  // your settings
  cookie: { secure: false }
}))

The best way to do things is to always let Express deal with it, if it can.最好的做事方式是始终让 Express 处理它,如果可以的话。

https://flaviocopes.com/express-sessions/ ( Updated Session tutorial although links should not be considered answers ) https://flaviocopes.com/express-sessions/ (更新会话教程,但链接不应被视为答案)

There's a link that can show you how to set up redis for sessions in Express.有一个链接可以向您展示如何为 Express 中的会话设置 redis。 You shouldn't have to even query redis yourself when dealing with sessions, that's a job for middleware in node.在处理会话时,您甚至不必自己查询 redis,这是节点中中间件的工作。

Maybe there are some asynchronous errors in your code.也许您的代码中有一些异步错误。 Every time you have the asynchronous operation(like a callback), you should make sure that your rest code is executed after the callback function, so you may put the code into the callback function.每次你有异步操作(比如回调)时,你应该确保你的rest代码在回调函数之后执行,这样你就可以将代码放入回调函数中。 Just like this:就像这样:

db.users.findOne({username: req.body.username}, function(err, user) {
  if( err ) {
    console.log("Login fail");
  } 
  else if (user != null) {
    if (req.body.password == user.password) {
      req.session.user_role = "user";
      req.session.save();
      res.send({redirect: "/"});
    } else {
      req.session.user_role = "null";
      console.log("Wrong login");
      res.send({redirect: "/"});
    }
  }
});

And the app.get should look like: app.get应如下所示:

app.get('/', function(req,res){
  redis.get('sess:' + req.session.id, function(err, result){
    console.log("Get session: " + util.inspect(JSON.parse(result),{ showHidden: true, depth: null }));
    if ((req.session.user_role == "user")) {
      console.log("Logged in");
    } else {
      console.log("Logged out");
    }
  });
});

If {secure:true} is set, and you access your site over HTTP, the cookie will not be set.如果设置了 {secure:true},并且您通过 HTTP 访问您的站点,则不会设置 cookie。 So, each request will create a new session.因此,每个请求都会创建一个新会话。

All answers so far are helpful but don't directly solve the issue with using secure:true.到目前为止的所有答案都有帮助,但不能通过使用 secure:true 直接解决问题。

In order to use secure:true you must have support for https for secure cookies.为了使用 secure:true,您必须支持 https 以获取安全 cookie。 Additionally you must use withCredentials for cross-site access control.此外,您必须使用 withCredentials 进行跨站点访问控制。 withCrendentials:true has no impact on same-site request. withCredentials:true 对同站请求没有影响。

https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/withCredentials https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/withCredentials

Majority of libraries support this parameter in their configurations such as angular and dropzone.大多数库在其配置中支持此参数,例如 angular 和 dropzone。

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

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