node.js - 没有使用 Node.js 和 express 设置 Cookie
问题描述
我正在尝试使用 Node.js 和 express 设置一个 cookie,但是当我签入 chrome 开发工具时,没有 cookie。我显然做错了什么,但不确定是什么。
在我的loginController.js我有
exports.postLogin = async (req, res) => {
const { email, password } = req.body;
const user = await authenticate(email, password);
if (!user) return res.status(403).send("Invalid email or password");
const userData = {
name: user.name,
email: user.email,
type: AUTH_USER_TYPE
};
res.cookie("token", userData, { httpOnly: true, signed: true });
res.json(userData);
};
在app.js我有:
const cookieParser = require("cookie-parser");
app.use(cookieParser(process.env.COOKIE_SECRET));
解决方案
您需要定义httpOnly: false
,例如:
res.cookie("token", userData, { maxAge: 1000 * 60 * 10, httpOnly: false });
在客户端,您需要发送withCredentials: true
请求
$http({
method: 'POST',
url: 'url,
withCredentials: true,
data : {}
}).then(function(response){
//response
}, function (response) {
//response
});
注意:httpOnly : false
将无法通过浏览器中的 document.cookie 访问。它仍然会与 HTTP 请求一起发送,如果您检查浏览器的开发工具,您很可能会发现 Chrome 中的 cookie 可以在开发工具的“资源”选项卡中找到。