每次发送新请求时,我的 express-session 都会被覆盖,我想知道是否是因为我的开发环境?反应+表达

My express-session is getting overwritten every time I send a new request, and I'm wondering if it is because of my dev environment? REACT + EXPRESS

编辑 - 我不再认为这是一个开发环境问题,因为同样的事情在生产中仍然存在。

首先,感谢花在这上面的时间 - 我知道这是一个常见的问题,但我仔细阅读了这么多问题,并尝试应用了这么多解决方案,但都无济于事。

总而言之,我目前有一个 React Front-end 正在使用 Fetch API 向我的 Express 服务器发送请求。我想使用 express-sessions 保存我的登录用户信息,供 session 在用户使用该应用程序时使用和验证。

我遇到了这个奇怪的问题,每次发送新请求时,应用程序选项卡中浏览器中的 cookie 都会设置为全新的内容。我可能理解错了,但我认为这应该在整个 session 中保持一致,但事实似乎并非如此。这样一来,每次我调用新请求时,req.session 都会完全重置。

这是我的应用程序中的一些代码:

Express- server.js [我对 express-session 和 cors 的设置]

app.use(cors({
  credentials: true
}))

const session = require('express-session')
// Middleware for creating sessions and session cookies.
// A session is created on every request
app.use(session({
  secret: 'tis a secret mate',
  cookie: {
    expires: 3000, // expires in 15 mins
    httpOnly: true,
    secure: false,
  },
  // Session saving options
  saveUnintialized: false, // don't save the initial session if the session object is unmodified (i.e the user did not log in)
  resave: true, // don't resave a session that hasn't been modified
  store: MongoStore.create({
    mongoUrl: process.env.MONGODB_URI_SESSIONS
  })

  }))

  app.use(function (req, res, next) {
    console.log('SESSION LOGGING MIDDLEWARE')
    console.log(req.session);
    next()
  });

app.use((req, res, next) => {
  res.header('Access-control-Allow-Origin', 'http://localhost:3000');
  res.header(
      "Access-Control-Allow-Headers",
      "Origin, X-Requested-With, Content-Type, Accept, Authorization"
  );
  res.header('Access-Control-Allow-Credentials', true);
  next();
  });

编辑 - 登录路径

app.post('/api/users/login', async (req, res) => {

  // pull out the body
  const body = req.body

  // pull out the username and password
  const username = body.username
  const password = body.password

  User.findByUsernamePassword(username, password)
    .then(user => {
      // if we find the user,  the users information to the session to retain all that information
      // will create a function to ensuree that the session exists to make sure that we are logged in
      req.session.user = user
      req.session.username = user.username
      req.session.save()
      console.log(req.session)
      res.send({ user: req.session.user })
    })
    .catch(error => {
      res.status(400).send()
    });
})

Front-end 获取调用 在下面的代码中,我将我的登录名和 check-session 调用粘贴到它们各自的端点。本质上,检查 session 只调用 returns session 中的内容,登录调用应该登录用户并将用户添加到 req.session.user

登录后,我尝试运行check-session查看用户是否在session,但不是每次都在。我还注意到 chrome 的应用程序选项卡中的 cookie 更改为其他内容。

export const login = (username, password, setUser) => {

  const obj = {
    username: username,
    password: password
  }

  const request = new Request(`${API_HOST}/api/users/login`, {
    method: "POST",
    credentials: "include",
    body: JSON.stringify(obj),
    headers: {
      "Content-Type": "application/json"
    }
  })

  // send the request
  const promise = fetch(request)
    .then(res => {
      if (res.status === 200) {
        return res.json();
      }
    })
    .then(json => {
      // if the user exists, setUser to user
      console.log("USER PRE:", json.user)
      if (json.user !== undefined) {
        console.log("USER: ", json.user)
        setUser(json.user)
        return json.user
      }
    })
    .catch(error => {
      console.log(error);
    })

  return promise
}

export const checkSession = () => {
  const url = `${API_HOST}/api/users/check-session`

  fetch(url, {
    credentials: 'include'
  })
  .then(res => {
      if (res.status === 200) {
          console.log('200')
          console.log(res.json())
      } else {
        console.log(res)
      }
  })
  // .then(json => {
  //     if (json) {
  //       setUser(json)
  //     }
  // })
  .catch(error => {
      console.log(error);
  });
}

我尝试过的事情

可能有用的附加说明

谢谢你的时间,我知道这是一个超长的问题。如果您想提供帮助,请让我知道是否还有其他任何我可以提供的帮助澄清!

如果您是 运行 不同主机上的后端和前端,则可能存在 CORS 问题。你还说你检查了应用程序选项卡中的 cookie,但如果你没有尝试查看网络选项卡中的请求和响应 cookie headers,你应该检查它们以进一步诊断问题。 cookie应该在身份验证请求中设置,并且应该包含在后面的请求中。