req.session 在浏览器上不持久?

req.session is not persistent on browser?

所以我有一个非常典型的查询。

我是新手,我正在使用存储在 MongoDB.

中的节点和快速会话构建一个简单的登录 Web 应用程序

这是我的代码:

sessionRouter.post("", async(req, res) => {
  try {
    const user = await User.findByCredentials(
      req.body.email,
      req.body.password
    );


    if (user) {
      const sessionUser = sessionizeUser(user);

      req.session.user = sessionUser;

      console.log(req.session.id);
      res.send(req.session.user);
    } else {
      throw new Error("invalid details.");
    }
  } catch (e) {
    res.status(400).send(e);
  }
});

//route to logout
sessionRouter.delete("", ({
  session
}, res) => {
  try {
    const user = session.user;

    if (user) {
      console.log(session.id);
      session.destroy((err) => {
        if (err) console.log(err);
        res.clearCookie(process.env.SESS_NAME);
        res.send(session.id);
      });
    } else {
      throw new Error("Something went wrong");
    }
  } catch (err) {
    console.log("things went wrong!");
    //res.status(422).send(JSON.stringify(err));
  }
});

当我调用登录 API 时,我将 'user' 属性存储到 req.session,但是当我调用注销 API 时,它会生成一个全新的会话!。

当我使用 postman 调用这些端点时一切顺利,但当使用浏览器时没有任何效果。

这些是我在浏览器中使用的调用函数:

const loggerin = () => {
  var myHeaders = new Headers();
  myHeaders.append("Content-Type", "application/json");
  myHeaders.append("Connection", "keep-alive");

  var raw = JSON.stringify({
    email: "xxxxxxxxxx",
    password: "xxxxxx",
  });

  var requestOptions = {
    method: "POST",
    headers: myHeaders,
    body: raw,
    redirect: "follow",
  };

  fetch("http://localhost:3001/api/session", requestOptions)
    .then((response) => response.text())
    .then((result) => console.log(result))
    .catch((error) => console.log("error", error));
};

const loggerout = () => {
  var myHeaders = new Headers();

  myHeaders.append("Content-Type", "text/plain");
  myHeaders.append("Connection", "keep-alive");

  var requestOptions = {
    method: "DELETE",
  };

  fetch("http://localhost:3001/api/session", requestOptions)
    .then((response) => response.text())
    .then((result) => console.log(result))
    .catch((error) => console.log("error", error));
};

const test = () => {
  var myHeaders = new Headers();

  myHeaders.append("Content-Type", "text/plain");
  myHeaders.append("Connection", "keep-alive");

  var requestOptions = {
    method: "GET",
  };

  fetch("http://localhost:3001/api/session", requestOptions)
    .then((response) => response.text())
    .then((result) => console.log(result))
    .catch((error) => console.log("error", error));
};

求助!!!提前致谢!

问题是我在错误的函数中创建了会话。我更正了它,它起作用了。