如何解决请求的资源上出现“Access-Control-Allow-Origin”标头错误?

问题描述 投票:0回答:1

当从实时服务器向后端进行 API 调用时,我遇到以下问题:

源“http://127.0.0.1:5500”已被 CORS 策略阻止:请求的资源上不存在“Access-Control-Allow-Origin”标头。如果不透明响应满足您的需求,请将请求模式设置为“no-cors”以在禁用 CORS 的情况下获取资源。

(实时服务器网址:网址为 http://127.0.0.1:5500/html/login.html)& 这是调用后端API的函数:

function handleGoogleLogin() {
  try {
    fetch("http://localhost:3000/api/auth/google", {
      method: "get",
    })
      .then((response) => {
        // Handle the response as needed (e.g., redirect to the authorization URL)
        if (response.ok) {
          window.location.href = response.url; // Redirect to Google OAuth URL returned by backend
        } else {
          console.error("Failed to initiate Google login");
        }
      })
      .catch((error) => {
        console.error("Error initiating Google login:", error);
      });
  } catch (error) {
    console.error("Error initiating Google login:", error);
  }
}

我什至在后端使用了Cors:

app.use(cors());

这些是我在后端的API:

AuthRouter.get(
  "/google",
  passport.authenticate("google", { scope: ["email", "profile"] })
);

AuthRouter.get(
  "/google/callback",
  passport.authenticate("google", { failureMessage: "Failed to authenticate" }),
  (req, res) => {
    //* Successful authentication, redirect home.
    return res.send({ message: "Successfully authenticated.", status: 200 });
  }
);

AuthRouter.get("/protected", isAuth, (req, res) => {
  return res.send({
    user: req.user,
    message: "Successfully authenticated.",
    status: 200,
  });
});


app.use("/api/auth", AuthRouter);

我什至在 Google Console 中添加了所有来源。

有人可以帮我吗?是什么导致了这个问题? 谢谢你。

node.js express cors google-oauth
1个回答
0
投票

你在哪里定义中间件(app.use(cors())?如果你在底部定义它可能不起作用。

© www.soinside.com 2019 - 2024. All rights reserved.