【问题标题】:Proxying API request from React frontend to Flask backend on two separate Heroku apps在两个单独的 Heroku 应用程序上代理从 React 前端到 Flask 后端的 API 请求
【发布时间】:2019-01-19 02:43:58
【问题描述】:

我正在开发一个带有 create-react-app 前端和带有 Flask-RESTful 的 Flask API 后端的 Web 应用程序。我在本地构建了该应用程序,它可以在我的计算机上运行,​​但现在我尝试将其部署到 Heroku 失败了。

我将 Flask 后端和 React 前端部署为两个不同的 Heroku dyno,因此每个都有自己的 URL。当我转到前端的 URL 时,它似乎工作正常,后端 URL 似乎也工作。但是,该应用依赖于对后端的 API 调用,我无法成功向后端发送请求。

当我在本地工作时,我会使用 gunicorn --bind 0.0.0.0:8000 app:app 运行烧瓶后端,使用 npm start 命令运行前端。只要我将"proxy": "https://localhost:8000" 放在我的前端应用程序中的package.json 文件中,该应用程序就可以很好地处理我的Axios 函数调用中的相关调用。一般来说,我遵循本教程:https://www.fullstackreact.com/articles/using-create-react-app-with-a-server/。

我想我可以简单地编辑 package.json 文件中的 proxy 字段以指向我的后端 Heroku 应用程序的 URL,然后我不必更改任何其他内容。但是,当我使用它进行部署时,我发现对我的端点的请求是发给https://my-frontend-app.herokuapp.com/<endpoint> 而不是https://my-backend-app.herokuapp.com/<endpoint>。

这是我的 package.json:

{
  "name": "heroku-app",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "axios": "^0.18.0",
    "bootstrap": "^4.1.2",
    "plotly.js": "^1.39.2",
    "react": "^16.4.1",
    "react-dom": "^16.4.1",
    "react-plotly.js": "^2.2.0",
    "react-scripts": "1.1.4",
    "reactstrap": "^6.3.0"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test --env=jsdom",
    "eject": "react-scripts eject"
  },
  "proxy": "https://star-employees-api.herokuapp.com"
}

我的请求如下所示:

axios.get('/analyze', data)
.then((response) => {
    // Handle request response here
};

谁能告诉我我在这里做错了什么?这是我第一次部署这样的应用程序并使用 Heroku,所以我不确定我是否离这里很远。如果有更好的方法来部署这种应用程序,也请告诉我。 如果有帮助,我可以提供任何其他代码 sn-ps 或文件结构,只是不确定此时会有什么帮助。提前致谢。

【问题讨论】:

  • proxy 字段仅用于开发中的 Webpack 开发服务器。您必须单独配置生产服务器。
  • @Tholle 我明白了,是否有任何资源可以做到这一点?根据我非常初级的研究,我需要使用 nginx 之类的东西来代替 webpack 开发服务器吗?感谢您的帮助!
  • 我自己从来没有在heroku上托管过任何东西,但是如果你可以使用nginxthis might be wroth a try。
  • 看起来我正在使用的 Heroku 的 create-react-app-buildpack 包含开箱即用的这种功能,如此处所述:github.com/mars/create-react-app-buildpack#proxy 我按照说明进行操作,但仍然没有为我工作。如果我找到解决方案,我会在 GitHub 上发布问题并发布答案。

标签: python reactjs heroku flask create-react-app


【解决方案1】:

我设法弄明白了。正如 Tholle 提到的,package.json 文件中的代理字段仅适用于开发服务器。如果您将 create-react-app 与 Heroku 和 buildpack 一起使用,还有其他一些步骤。部署时,您需要按照说明here 并在最顶层目录中添加一个static.json 文件。

【讨论】:

  • 如果您在同一个测功机上同时运行服务器和客户端,您将如何进行设置?
猜你喜欢
  • 1970-01-01
  • 2020-02-13
  • 1970-01-01
  • 1970-01-01
  • 2020-01-06
  • 2018-04-08
  • 1970-01-01
  • 2020-01-01
  • 2020-06-16
相关资源
最近更新 更多