【发布时间】:2022-02-09 00:11:49
【问题描述】:
我正在开发我的最终项目,并且我正在尝试构建一个 MERN 项目。我正在尝试使用护照实现身份验证,它在开发中工作,但是当我部署时,我不断收到此错误
CORS 策略已阻止从源“http://localhost:3000”访问“https://hospitalveterinariopeninsular.herokuapp.com/api/auth/googleLogin/success”获取:否“访问控制-请求的资源上存在 Allow-Origin' 标头。如果不透明的响应满足您的需求,请将请求的模式设置为“no-cors”以获取禁用 CORS 的资源。
但如果我手动访问该站点:https://hospitalveterinariopeninsular.herokuapp.com/api/auth/googleLogin/success',我会得到我需要的响应。所以不知道是服务器的问题还是 React 的问题。
这是我在服务器中的代码:
Index.js
const app = express();
app.use(
cookieSession({ name: "session", keys: ["whatever"], maxAge: 24 * 60 * 60 * 100 })
);
app.use(passport.initialize());
app.use(passport.session());
dbConnection();
// CORS
app.use(
cors({
origin: process.env.CLIENT_URL,
methods: "GET,POST,PUT,DELETE, PATCH",
credentials: true,
maxAge: 3600,
})
);
app.use(express.static(path.join(__dirname, "/public")));
app.use(express.json());
app.use("/api/auth", authRoutes);
AuthRoutes.js
router.get(
"/google",
passport.authenticate("google", { scope: ["profile", "email"] })
);
// callback from google
router.get(
"/google/callback",
passport.authenticate("google", {
failureRedirect: "/api/auth/googleLogin/failed",
successRedirect: `${process.env.CLIENT_URL}/#/auth`,
})
// googleAuth
);
router.get("/googleLogin/success", (req, res) => {
console.log("success", req.user);
if (req.user) {
res.status(200).json({
success: true,
message: "successfull",
user: req.user,
token: req.user.token,
// cookies: req.cookies
});
}
});
来自 React 的代码
export const AuthPage = () => {
useEffect(() => {
const getUser = () => {
fetch(`${process.env.REACT_APP_API_URL}/auth/googleLogin/success`, {
method: "GET",
credentials: "include",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
"Access-Control-Allow-Credentials": true,
},
})
.then((response) => {
console.log("THIS IS THE RESPONSE", response);
if (response.status === 200) return response.json();
throw new Error("authentication has been failed!");
})
.then((resObject) => {
console.log("POR FAVOR********", resObject);
localStorage.setItem("token", resObject.token);
localStorage.setItem("token-init-date", new Date().getTime());
dispatch(startChecking());
})
.catch((err) => {
console.log(err);
});
};
getUser();
}, []);
return (...);
};
编辑以添加 github 链接 后台:https://github.com/JavierGarciaGomez/hvp2021backend 前端:https://github.com/JavierGarciaGomez/hvp2021frontend
环境变量:
React:
REACT_APP_API_URL=https://hospitalveterinariopeninsular.herokuapp.com/api
Node:
PORT=4000
CLIENT_URL=http://localhost:3000
CLIENT_URL_PROD=https://www.hospitalveterinariopeninsular.com
【问题讨论】:
-
您是否设置/更新了
process.env.CLIENT_URL环境变量以使其反映正确的来源? -
local和heroku中process.env.CLIENT_URL的值是多少?
-
是的,在 heroku 中正确设置为环境变量:hospitalveterinariopeninsular.com 实际上,当调用 router.get("/google/callback", (...)) 时,它会重定向我正确到hospitalveterinariopeninsular.com/#/auth
-
@BaoHuynhLam 刚刚尝试过,而不是重定向到该站点,而是转到此处:/api/auth/google/www.hospitalveterinariopeninsular.com/ 很奇怪,我想了解原因