繁体   English   中英

如何从 node/express 中的后端(端口:3001)路由重定向到前端(端口:3000)?

[英]How do I redirect to front-end (port: 3000) from a back-end (port:3001) route in node/express?

我在端口 3001 上定义了所有后端 API,我想重定向到端口 3000 的前端路由。有没有办法做到这一点?

我知道我可以简单地执行以下操作

router.get(
  "/steam/return",
  passport.authenticate("steam", {
    failureRedirect: "/",
    session: true,
  }),
  function (req, res) {
    return res.redirect("http://localhost:3000");
  }
);

但是假设我将其部署到 Heroku 生成自己的唯一域,我将如何“动态”将前端路由传递给应用程序?

假设 heroku 生成some-domain.herokuapp.com然后我想重定向到该域。 但同时在我的开发版本中,我想重定向到http://localhost:3000

根据ArchNoob的反馈,我可以通过检查process.env.NODE_ENV来解决这个问题。 此环境变量在项目部署到 heroku 时设置为生产; heroku 默认执行此操作。

然后在我的护照策略中,我做了:

// port 3443 is for my api routes
const returnURLString =
    process.env.NODE_ENV === "production"
      ? "https://my-app.herokuapp.com/api/auth/steam/return"
      : "http://localhost:3443/api/auth/steam/return";

  const realmString =
    process.env.NODE_ENV === "production"
      ? "https://my-app.herokuapp.com/"
      : "http://localhost:3443/";
  passport.use(
    new SteamStrategy(
      {
        returnURL: returnURLString,
        realm: realmString,
        apiKey: myAPIKey,
      },
  ...

在我的 API 返回路线中,我做了:

router.get(
  "/steam/return",
  passport.authenticate("steam", {
    failureRedirect: "/",
    session: true,
  }),
  function (req, res) {
    const env = process.env.NODE_ENV || "dev";
    if (env === "production") {
      return res.redirect("https://my-app.herokuapp.com/");
    } else {
      return res.redirect("http://localhost:3000");
    }
  }
);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM