我想將 jwt 令牌作為 cookie 從 express.js(后端)存盤到 react.js(前端)。我還安裝了該cookie-parser軟體包并在 main.js 檔案(服務器端)中使用它,并使用res.cookies. 如果我嘗試使用郵遞員,郵遞員會顯示 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),
});
}
};
反應代碼在這里:
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",
})
};
uj5u.com熱心網友回復:
根據https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies
JavaScript Document.cookie API 無法訪問具有 HttpOnly 屬性的 cookie;它只發送到服務器。例如,在服務器端會話中持續存在的 cookie 不需要對 JavaScript 可用,并且應該具有 HttpOnly 屬性。這種預防措施有助于緩解跨站點腳本 (XSS) 攻擊。
簡單地改變
httpOnly: true
至
httpOnly: false
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/497755.html
標籤:javascript 反应 表示 饼干 梅尔
