cookie不存储在MERN堆栈的客户端



我想将jwt令牌作为cookie从express.js(后端)存储到react.js(前端)。我还安装了cookie-parser包,并在main.js文件(服务器端)中使用它,并使用res.cookies创建cookie。如果我尝试使用邮递员,邮递员会显示cookie成功生成,但如果我尝试使用react,则cookie不会被存储。

表达代码:

const login = async (req, res, next) => {
try {
// geting the user email and the password
const { userEmail, userPass } = req.body;
// 1st we are checking that email and the password are existing
if (!userEmail || !userPass) {
return next("Plz enter valid email and password");
}
console.log(userEmail, userPass);
// 2nd if usre is existing than password is correct or not
const user = await userModel.findOne({ userEmail }).select("+password");
const correct = await user.correctPassword(userPass, user.password);
if (!userEmail || !correct) {
return next("Wrong credentials");
}
// 3rd if everything is ok then we send the token to the client
const userToken = signToken(user._id);
// here we passing the token by using cookie
res.cookie("jwt", userToken, {
expires: new Date(Date.now() + 500000),
httpOnly: true,
secure: false,
});
// console.log(userToken);
res.status(200).json({
status: " successfully Login",
});
} catch (error) {
res.status(400).json({
status: "fail",
data: next(error),
});
}
};

React代码在这里:

const Login = () => {
const [userLogin, setUserLogin] = useState({
userEmail: "",
userPass: "",
});
let name, value;
const handelInputs = (e) => {
name = e.target.name;
value = e.target.value;
setUserLogin({ ...userLogin, [name]: value });
};
const log = async () => {
const response = await axios.post("/login", userLogin, {
withCredentials: true,
credentials: "include",
})
};

按照https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies

带有HttpOnly属性的cookie对JavaScript文档是不可访问的。饼干的API;它只被发送到服务器。例如,在服务器端会话中持久化的cookie不需要对JavaScript可用,并且应该具有HttpOnly属性。此预防措施有助于减轻跨站点脚本(XSS)攻击。

简单地改变

httpOnly: true

httpOnly: false

最新更新