来自快速会话的会话不会通过请求持续存在

Session from express-session not persisting through requests

我正在使用 express-session 并尝试使用自定义中间件实现受保护的路由。

[注意:我目前正在内存中存储我的会话]

app.use(
  session({
    secret: "f4z4gs$Gcg",
    cookie: { maxAge: 300000000, secure: true },
    saveUninitialized: false,
    resave: false,
    store,
  })
);

// MIDDLEWARE
function ensureAuthenticated(req, res, next) {
  console.log(req.session) //  This doesn't show the user and authenticated properties created in the POST login request
  if (req.session.authenticated) {
    return next();
  } else {
    res.status(403).json({ msg: "You're not authorized to view this page" });
  }
};

app.post("/login", (req, res) => {
  const { username, password } = req.body;

  db.users.findByUsername(username, (err, user) => {
    if (user) {
      if (user.password === password) {
        // Add your authenticated property below:
        req.session.authenticated = true;
        // Add the user object below:
        req.session.user = {
          username,
          password,
        };
        // Send the session back to the client below:
        res.json(req.session); // Properties show up here
      } else {
        res.status(403).json({ msg: "Bad Credentials" });
      }
    } else {
      res.status(403).json({ msg: "No user found!" });
    }
  });
});


// PROTECTED ROUTE
app.get("/protected", ensureAuthenticated, (req, res) => {
  res.render("profile");
});

用户成功登录后,我尝试将两个属性添加到 req.sessionauthenticateduser 对象。但是,一旦我登录并尝试使用中间件访问 /protected,我的会话属性就不会持续存在(没有 userauthenticated 属性)。我错过了什么吗?

尝试在 cookie 对象中将 secure 设置为 false。如果您希望它是 httpOnly,则只需将 httpOnly 设置为 true。