快速会话在一段时间后停止保存会话

时间:2018-06-12 09:01:01

标签: javascript node.js mongodb express session

我有一个相当难以捉摸的问题,快递在大约一天的正常运行时间后会在会话存储(MongoDB)或客户端cookie中保存会话数据。重新启动服务器端API服务器似乎解决了这个问题,但仅在另一天左右,然后再次出现并且必须重新启动。

节点应用程序在Ubuntu 16上运行,我找不到与此问题相关的任何日志消息。

我将粘贴下面设置会话数据的登录代码

router.post('/login', async function(req, res) {
var user_name = req.body.user_name;
var password = req.body.password;
var currentTime = new Date().getHours() + ":" + new Date().getMinutes();

if(user_name && password) { // If both the username and password were sent.
  User.findOne({"field_data.user_name": user_name}).select('password 
  field_data').then( async (user) => {
    if(!user) { // A record was not found.
      console.log(currentTime + " - Failed Login: " + user_name);
      var returnResult = {
        error: true,
        msg: "User Not Found."
      };
      res.json(returnResult);
    } else { // A record was found.
      console.log(currentTime + " - User Logged in: " + 
      user.field_data.first_name + " " + user.field_data.last_name);
      let result = await user.CheckCredentials(password);
      if(result) {
        var returnResult = {
          error: false,
          msg: "Logged In: " + user.field_data.first_name + " " + 
          user.field_data.last_name,
          data: {
            first_name: user.field_data.first_name,
            last_name: user.field_data.last_name,
            user_roles: user.field_data.user_role,
            id: user._id
          }
        };

        // Set session data which creates record in session store and client 
        // cookie.
        req.session.userId = user.id;
        req.session.userRoles = user.field_data.user_role ;
        req.session.userName = user.field_data.first_name + " " + 
        user.field_data.last_name;
        req.session.save(); // This line makes no difference.

      } else {
        var returnResult = {
          error: true,
          msg: "Invalid Credentials!"
        };
      }
      res.json(returnResult);
    }

  }).catch((e) => {
    console.log(e)
  });
} else {
  res.json({error: true, msg: "Invalid username/password!"});
}
});

1 个答案:

答案 0 :(得分:0)

我认为您的会话maxAge即将到期。 我使用redis你可以随意进行更改

var express = require("express");
var session = require('express-session');

var sessionConfig = {
    secret: "your_secret",
    store: // new redisStore({ client: redis.getClient() }),
    resave: true,
    rolling: true,
    saveUninitialized: true,
    cookie: { maxAge: 30 * 60000 }
}

var app = express();
app.use(session(sessionConfig));

app.post('/somepath', (req,res,next)=>{
        // find your user or else 
        req.session.userData = {
            id : user.id,
            roles : user.field_data.user_role ,
            name : user.field_data.first_name
        }
});