我正在从后端API发送cookie(仅HTTP cookie)。当我使用postman发送请求时,cookie设置在头部(Set-Cookie)中,但当我尝试使用redux从前端发送请求时,cookie不会出现在浏览器cookie
browser image
Postman image中
respond header有cookie image of the respond header
userController.js
// Public
// /users/login GET
// auth user
const authUser = asyncHandler(async (req, res) => {
const { email, password } = req.body;
if (!email || !password) {
res.status(403);
throw new Error("email or password empty");
}
const user = await User.findOne({ email });
if (!user) {
res.status(404);
throw new Error("user not found");
}
if (bcrypt.compareSync(password, user.password)) {
//generate jwt token and send it
genToken(res, user._id);
res.status(200).json({
message: "User logged in",
user: {
id: user._id,
name: user.name,
email: user.email,
},
});
} else {
res.status(401);
throw new Error("email or password not correct");
}
});
字符串
genToken.js
const genToken = (res, userId) => {
const token = jwt.sign({ userId }, process.env.JWT_SECRET, {
expiresIn: "30d",
});
// set jwt hhtp cookie on the server
res.cookie("jwt", token, {
httpOnly: true,
secure: false, //////////////// development only
sameSite: "strict",
maxAge: 30 * 24 * 60 * 60 * 1000, // 30 days,
});
};
型
还原/auth的端点
login: builder.mutation({
query: (data) => ({
url: `${USERS_URL}/auth`, // USER_URL=/users
method: "POST",
body: data,
}),
}),
型
我使用扩展moesif禁用了浏览器的CORE
并安装了“cors”包
server.js
import express from "express";
import cors from "cors";
const app = express();
var corsOptions = {
origin: "*",
optionsSuccessStatus: 200, // some legacy browsers (IE11, various SmartTVs) choke on 204,
credentials: true,
};
app.use(cors(corsOptions));
型
但没有成功
1条答案
按热度按时间uqcuzwp81#
成功了。
首先将origin设置为“http://localhost:5173”,并在redux查询中将凭据设置为“include”,在token选项中将sameSite设置为“lax”,并禁用灭绝