I am making a full stack ecommerece website but when i login the backend send an object containing token , success message and user details but the thing to access the other function i have made an isVerified function which gets the token from cookie and checks it , i have tested all the function in Postman and they were working but in frontend they are not working as they keep saying req.cookie.token undefined
I want that token to be stored in cookie in frontend and be accesible
使用的技术是React Js,Express js 浏览器是Chrome 我已经尝试了一切请有人帮助我 我尝试使用 secure 删除 ,将 http 从 true 设置为 false 使用 cors 设置应用程序并使用凭证 true ,
// Code
Login function in Frontend
const handleSubmit = async (e) => {
e.preventDefault();
const user = { email, password };
const response = await login(user);
if (response.error) {
console.error('Login error:', response.error);
} else {
Cookies.set('token', response.token, { expires: 7, sameSite: 'lax' });
setUser(response.user);
console.log('Login successful:', response);
navigate('/');
}
};
Auth middleware in backend
const isVerified = async (req, res, next) => {
const token = req.cookies.token;
console.log(token);
if (!token) {
return next(new ErrorHandler("Login first to access this resource", 401));
}
const decoded = jwt.verify(token, process.env.JWT_SECRET);
req.user = await User.findById(decoded.id);
next();
};
// Util send token function
// Creating a token and sending it in a cookies
const sendToken = (user, statusCode, res) => {
const token = user.getJwtToken();
const options = {
expires: new Date(
Date.now() + process.env.COOKIE_EXPIRES_TIME * 24 * 60 * 60 * 1000
),
httpOnly: false,
};
res.status(statusCode).cookie("token", token, options).json({
success: true,
token,
user,
});
};
module.exports = sendToken;
只是猜测,但可能是因为您的请求中没有包含凭据。 Mdn
fetch("https://example.com", {
credentials: "include",
});
您还可以使用 DevTools -> 应用程序选项卡 -> Cookies 检查客户端是否设置了 cookie。
此外,可能需要调整服务器上的 cookie 配置。