【发布时间】:2021-03-03 20:17:09
【问题描述】:
我有一个在 localhost:5000 上运行的快速服务器和在端口 3000 上运行的客户端。 从客户端发送 post 请求以使用 fetch API 登录后,浏览器未设置 cookie。我在响应标头中将 cookie 设置为“set-cookie”,但它没有在客户端的浏览器中设置。
这是我的获取请求代码:
return (
fetch(baseUrl + "users/login", {
method: "POST",
body: JSON.stringify(User),
headers: {
"Content-Type": "application/json",
},
credentials: "same-origin",
})
服务器端代码:
router
.route("/login")
.options(cors.corsWithOptions, (req, res) => {
res.sendStatus(200);
})
.post(cors.corsWithOptions, (req, res, next) => {
passport.authenticate("local", (err, user, info) => {
if (err) return next(err);
if (!user) {
res.statusCode = 401;
res.setHeader("Content-Type", "application/json");
res.json({ success: false, status: "Log In unsuccessful", err: info });
}
req.logIn(user, (err) => {
if (err) {
res.statusCode = 401;
res.setHeader("Content-Type", "application/json");
// res.header("Access-Control-Allow-Credentials", true);
res.json({
success: false,
status: "Login Unsuccessful!",
err: "Could not log in user!",
});
}
var token = authenticate.getToken({ _id: req.user._id });
res.cookie("jwt-token", token, {
signed: true,
path: "/",
httpOnly: true,
});
res.statusCode = 200;
res.setHeader("Content-Type", "application/json");
res.json({ success: true, status: "Login Successful!", token: token });
});
})(req, res, next);
});
【问题讨论】:
-
如果您在 Stack Overflow 上需要帮助,请不要发送您的代码图片你的问题
-
我已经改了。请立即提供帮助
-
哦,好吧,我在这里看到您正在尝试使用服务器端会话 cookie 我将给出解决方案,我将给出 express-session 和 mongoDb...但是从您的代码中我看到您正在发送许多有效负载数据,但您也应该只在 cors 设置中发送 token only你需要一些配置设置,你会在我的回答中看到
标签: node.js cookies fetch cross-domain