我已经查看了其他相关的帖子,但都对我没有用。我在客户端使用vue,在服务器端使用node。
我尝试了其他帖子中建议的使用cors库的方法,但没有成功。 人们可能会认为下面的代码可以让我从客户端的localhost:8080发送请求到服务器的localhost:3000,但是所有的请求都失败了。
const cors = require("cors");
if (process.env.ENV !== "prod") {
let corsOptions = {
origin: ["http://localhost:8080"],
credentials: true,
optionsSuccessStatus: 200,
};
app.use(cors(corsOptions));
}
这是我用于设置cookie的控制器。
router.route("/login").post(async (req, res) => {
//Authenticate users
const user = await Users.findOne({ where: { email: req.body.email } });
if (user == null) {
return res.status(400).send("找不到用户!");
}
try {
if (await bcrypt.compare(req.body.password, user.password)) {
const userInfo = {
username: user.username,
email: user.email,
age: user.age,
};
const accessToken = generateAccessToken(userInfo);
const refreshToken = jwt.sign(userInfo, process.env.REFRESH_TOKEN_SECRET);
res.cookie("token", accessToken, {
maxAge: 300000,
secure: true,
httpOnly: true,
sameSite: "none",
});
res.status(200).send("登录成功!");
} else {
res.send("邮箱或密码不正确!");
}
} catch {
res.status(500).send();
}
});
这个网站上的每个答案基本上都会回到app.use(cors),但出于某种原因,对我不起作用。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号