我已经在www.example.com上设置了我的react应用程序xxx.herokuapp.com,在yyy.herokuapp.com上设置了我的node应用程序。两者都能正常工作,我是后端,能够将数据发送到前端。但是当我想发送cookie时,没有设置cookie。它在本地主机中工作,但在生产中不工作。我还使用cookieParser处理cookie。代码如下:
index.js:
app.use(
cors({
origin: [
"http://localhost:3000",
"https://xxx.herokuapp.com",
"https://yyy.herokuapp.com",
],
credentials: true,
})
);
auth.js:
export const signin = async (req, res, next) => {
try {
const user = await User.findOne({ username: req.body.username });
if (!user) return next(createError(404, "User does not exist!"));
const verifyPassword = bcrypt.compareSync(req.body.password, user.password);
if (!verifyPassword) return next(createError(400, "Invalid credentials!"));
const token = jwt.sign({ id: user._id }, process.env.JWT_KEY);
const { password, ...others } = user._doc;
res
.cookie("access_token", token, {
httpOnly: true,
})
.status(200)
.json(others);
} catch (error) {
next(error);
}
};
React:
const handleLogin = async (e) => {
e.preventDefault();
dispatch(loginStart);
try {
setOpen(true);
setAlert({ message: "Logged in.", severity: "success" });
const res = await axios.post(`${SERVER_URL}/auth/signin`, userForm, {
withCredentials: true,
});
dispatch(loginSuccess(res.data));
navigate("/");
// window.location.href = "/";
} catch (error) {
dispatch(loginFailure());
setOpen(true);
setAlert({
message: error.response.data.message,
severity: "error",
});
}
};
1条答案
按热度按时间i2byvkas1#
必须将{sameSite:“无”,安全:false}在资源Cookie中