【问题标题】:MERN, passport, blocked by CORS policy. "No access-control-allow-origin headerMERN,护照,被 CORS 政策阻止。 "没有访问控制允许来源标头
【发布时间】: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

【问题讨论】:

标签: reactjs cors mern


【解决方案1】:

订单对 express 中间件高度敏感。

在你的入口点你有这个:

app.use(passport.initialize());
app.use(passport.session());

...

// CORS
app.use(
  cors({
    origin: process.env.CLIENT_URL,
    methods: "GET,POST,PUT,DELETE, PATCH",
    credentials: true,
    maxAge: 3600,
  })
);

将 cors 初始化放在护照初始化之前:

// CORS
app.use(
  cors({
    origin: process.env.CLIENT_URL,
    methods: "GET,POST,PUT,DELETE, PATCH",
    credentials: true,
    maxAge: 3600,
  })
);

....

app.use(passport.initialize());
app.use(passport.session());

我认为您的 cors 配置没有检测到您的护照路线,因为那些配置 cors 魔法之前

【讨论】:

  • 更改时出现同样的错误
猜你喜欢
  • 2020-08-23
  • 2020-07-26
  • 2021-11-03
  • 2021-08-07
  • 2021-12-24
  • 1970-01-01
  • 2019-09-16
  • 2020-11-02
  • 2021-12-09
相关资源
最近更新 更多