I want to store the jwt token as a cookie from express.js(backend) to react.js(frontend). I also installed the cookie-parser
package and use it in the main.js file(server-side) and create the cookies by using res.cookies
. if I try with the postman, the postman shows cookies generate successfully but if I try with the react then cookies are not stored.
express code:
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 code is here:
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",
})
};
CodePudding user response:
As per https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies
A cookie with the HttpOnly attribute is inaccessible to the JavaScript Document.cookie API; it's only sent to the server. For example, cookies that persist in server-side sessions don't need to be available to JavaScript and should have the HttpOnly attribute. This precaution helps mitigate cross-site scripting (XSS) attacks.
Simply change
httpOnly: true
to
httpOnly: false