【问题标题】:Deploy the backend and frontend on the same Heroku app/dyno在同一个 Heroku app/dyno 上部署后端和前端
【发布时间】:2016-07-30 00:32:05
【问题描述】:

在我的项目的根目录下,我有一个 frontendbackend 文件夹。这两个文件夹都包含一个package.json,列出了它们的依赖关系。部署应用程序时,如何告诉 Heroku 在两个文件夹上运行 npm install? Heroku 似乎希望默认有一个 package.json 文件。我必须对 Procfile 做些什么吗? Heroku 文档似乎没有说明我的具体问题。

感谢您的帮助!

【问题讨论】:

    标签: node.js heroku deployment procfile dyno


    【解决方案1】:

    看来你可以在项目的根目录下放一个package.json 文件,并使用脚本在两个文件夹中调用npm i

    https://devcenter.heroku.com/articles/nodejs-support#customizing-the-build-process

    类似cd front && npm i && cd ../back && npm i

    但我应该说,如果它们在不同的端口上运行,它可能无法正常工作,因为每个 procfile 似乎只有一个 Web 进程可用。 最后一点是为了确认。

    【讨论】:

    • 是的,我已经这样做了,虽然你不能在构建过程中使用cd(如果你这样做,Heroku 会给出一个错误并使你的构建失败),你需要做一些事情喜欢:"npm --prefix ./front install"。我希望有一种更 Heroku“原生”的方式来做这件事。如果在赏金结束前我没有得到这样的答案,我会奖励你赏金。请使用我刚刚提供的信息更新您的答案。谢谢!
    • 或使用安装后挂钩
    【解决方案2】:

    您可以在Procfile 中为您的项目定义多个入口点:

    web: cd front && npm i && npm start
    server: cd backend && npm i && npm start
    

    但是,您至少必须升级到 Hobby。这是 7 美元/dyno/月。

    【讨论】:

      【解决方案3】:

      我刚刚使用在 heroku 后期构建步骤中创建的静态文件成功完成了这个目标,如blogpost 中所述。我有一个 React 前端(虽然可以是任何东西)和 Express API 后端。每个进程在 dev 中都有自己的端口,但在 Heroku 上部署总共只使用一个。

      1. 将工作前端放在根目录下(如/frontend)。
      2. 将工作后端放在根目录的子目录中(例如/api - 博文假定后端保留在根目录中 - 无论哪种方式都可以)。
      3. 通过将此行添加到 /frontend/package.json(将 5000 替换为您的后端端口)从前端到后端的代理 API 请求:

        “代理”:“http://localhost:5000”,

      4. 将以下内容添加到后端的api/app.js(或api/index.js)(确保最后一部分是在您定义适当的后端[或api]路径之后):

      const path = require('path')
      
      // Serve static files from the React frontend app
      app.use(express.static(path.join(__dirname, '../frontend/build')))
      
      // AFTER defining routes: Anything that doesn't match what's above, send back index.html; (the beginning slash ('/') in the string is important!)
      app.get('*', (req, res) => {
        res.sendFile(path.join(__dirname + '/../frontend/build/index.html'))
      })
      1. 编辑根目录的/package.json 文件,如下所示(请注意,使用并发包可以轻松地使用npm run dev 在本地运行整个应用程序,但此处只需要heroku-postbuild):李>

        "scripts": {
          "frontend": "cd frontend && npm start",
          "api": "cd api && nodemon app.js",
          "dev": "concurrently --kill-others-on-fail \"npm run api\" \"npm run frontend\"",
          "heroku-postbuild": "cd frontend && npm install && npm run build"
        },
      1. 确保将所有后端包依赖项安装在根目录中,否则会出错。
      2. 确保您的/Procfile 有类似web: node api/app.js 的内容

      【讨论】:

      • 感谢您的详细解释。但是 Heroku 不允许我设置自己的端口,那么我将在 package.json 中的“代理”中填写什么?
      • 添加 ENV 变量怎么样?我们应该在哪里做?
      猜你喜欢
      • 2020-11-11
      • 2021-02-14
      • 1970-01-01
      • 2020-11-28
      • 1970-01-01
      • 2022-11-04
      • 1970-01-01
      • 2021-02-23
      相关资源
      最近更新 更多