node.js - 如何将快速会话发送到不在同一个 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 });
});
});
});
解决方案
推荐阅读
- c# - Windows Form c# - 将 RichTextBox 中的每一行插入到 SQL Server 的单独列中
- android - 对于 api 21 和 22 棒棒糖版本,带有滚动视图的 Android 布局不可见
- python - 如何通过 Keycloak API 获取客户端密码?
- angular - Angular5 Ngx-chart:甜甜圈图 - 内外标签
- spring - Spring 安全测试:如何模拟/监视 JWK 等安全密钥类
- laravel - 从 Laravel 发送自定义 500 http 响应
- scala - Scala - 如何根据 Future 过滤 Seq
- postgresql - 在 Postgresql 中使用子查询进行查询
- firebase - 在 Firestore 中存储小图像是否安全?
- vue.js - 未找到 Vue-cli-service@latest