首页 > 解决方案 > 如何将快速会话发送到不在同一个 url 中的客户端?

问题描述

我能得到一些帮助吗,我一直在互联网上搜索这个,我似乎找不到我正在寻找的答案。

所以我很想将表达式会话和 mongoDB 实现为存储,所以我设法完成会话创建并将会话保存在存储中,即 MongoDB 设法完成。

现在问题来了,当我必须将会话 cookie 发送到客户端时,我的服务器(NodeJS)在端口 5000 上运行,客户端(ReactJS)在端口 3000 上运行,所以现在我该如何发送那个 cookie到客户端并将其标记为 httpOnly cookie?

这就是我尝试设置快速会话的方式

mongoose
  .connect(MongoURI, {
    useNewUrlParser: true,
    useCreateIndex: true
  })
  .then(() => console.log("MongoDB connected..."))
  .catch((err) => console.log(err));
const mongoDBstore = new MongoDBStore({
  uri: MongoURI,
  collection: "mySessions"
});
app.use(express.urlencoded({ extended: false }));
app.use(express.json());
app.use(
  session({
    name: COOKIE_NAME, 
    secret: 'SESS_SECRET',
    resave: true,
    saveUninitialized: false,
    store: mongoDBstore,
    cookie: {
      maxAge: 1000 * 60 * 60 * 3,
      sameSite: false,
      secure: false
    }
  })
);

这是我想在用户登录后发送 cookie 的地方

router.post("/login", (req, res) => {
  const { email, password } = req.body;
  if (!email || !password) {
    return res.status(400).json({ msg: "Please enter all fields" });
  }
  User.findOne({ email }).then((user) => {
    if (!user) return res.status(400).json({ msg: "User does not   exist" });
    bcrypt.compare(password, user.password).then((isMatch) => {
      if (!isMatch) return res.status(400).json({ msg: "Invalid    credentials" });
      const sessUser = { id: user.id, name: user.name, email:   user.email };
      req.session.user = sessUser; 
      res.json({ msg: " Logged In Successfully", sessUser });
    });
  });
});

标签: node.jsreactjsmernexpress-session

解决方案


推荐阅读