如何在 Heroku 平台上从 React 客户端向 Express 服务器 运行 发出 API 请求

How to make API request from react client to express server running on the Heroku platform

我一直在尝试使用 React、redux、节点媒体服务器和 json 服务器模块将类似 Twitch 的应用程序部署到 Heroku。但是,在生产过程中,当我尝试通过 api 请求连接我的反应客户端和快速服务器时,我一直 运行 遇到问题。

我试图通过我的 action creators 和使用基数 url 为 http://localhost:4000 的 axios 发出实际请求,但这只适用于我的本地机器。

 const response = await streams.get("/streams");

 dispatch({ type: FETCH_STREAMS, payload: response.data });
}; 

您可以在 https://github.com/XorinNebulas/Streamy

查看我的完整存储库

您还可以在 Heroku 上查看我当前部署的站点版本,网址为 https://streamy-app.herokuapp.com/

这是我的 api/server.js 文件。我的快速服务器将在等于 process.env.PORT 的随机端口上进行监视,因此我无法知道如何在生产期间通过我的动作创建者向该随机端口发出网络请求。

const path = require("path");
const cors = require("cors");
const jsonServer = require("json-server");
const server = jsonServer.create();
const router = jsonServer.router("db.json");
const middlewares = jsonServer.defaults({
  static: "../client/build"
});
const PORT = process.env.PORT || 4000;

// Set default middlewares (logger, static, cors and no-cache)
server.use(cors());
server.use(middlewares);

if (process.env.NODE_ENV === "production") {
  // Add custom routes before JSON Server router
  server.get("*", (req, res) => {
    res.sendFile(
      path.resolve(__dirname, "../", "client", "build", "index.html")
    );
  });
}

// Use default router
server.use(router);
server.listen(PORT, () => {
  console.log(`JSON Server is listening on port ${PORT}`);
});

我希望请求能够通过并从 api/db.json 加载一些数据,并带有 https://streamy-app.herokuapp.com/streams but instead i got a request url of http://localhost:4000/streams 的请求 url,这当然会导致下面的 CORS 问题

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:4000/streams. (Reason: CORS request did not succeed).

我真的很感激任何建议,我已经为此工作了好几天。

首先,您应该知道 Heroku 不允许 暴露多个端口,这意味着您应该将多个端口的方法更改为其他方法(参见 ).

其次,文件 client/src/apis/streams.js 被硬编码配置为向 http://localhost:4000/ 发送请求 - 这不是一个好主意。
无论您选择哪种方法 - 即使部署到另一台主机服务器 - 您都需要根据环境动态配置 API 端点。

我还建议您:

  1. 更改部署 React 的方式,如 here 所述。
  2. 完成以上操作后,考虑将您的API服务与静态服务器合并,这样您就不需要多个端口,然后一切变得更容易。

好的,看来我明白了。我只是进入 streams/client/package.json 并添加

"proxy":"http://localhost:4000" 

然后我进入 streams\client\src 并删除了 api 文件夹,其中包含我的自定义 axios,基数 url。为我的动作创作者使用开箱即用的 axios

const response = await axios.get("/streams");

 dispatch({ type: FETCH_STREAMS, payload: response.data });
}; 

现在 运行 在本地处于开发模式时,我可以向 http://localhost:4000/streams, but after deploying my node app to Heroku I successfully make a request over to https://streamy-app.herokuapp.com/streams 发出请求 希望这对遇到更棘手问题的人有所帮助。