在同一个Heroku app/dyno上部署后端和前端

max*_*pre 15 deployment heroku node.js procfile dyno

在我的项目的根目录,我有一个frontendbackend文件夹.两个文件夹都包含package.json列出其依赖项的文件夹.npm install在部署应用程序时,如何告诉Heroku 在两个文件夹上运行?Heroku似乎希望package.json默认情况下只有一个文件.我是否必须使用Procfile执行某些操作?Heroku文档似乎没有说明我的具体问题.

谢谢您的帮助!

Mic*_* S. 13

我刚刚成功完成了使用过程中的Heroku postbuild一步创建静态文件这一目标,如在此描述的博文。我有一个 React 前端(可以是任何东西)和 Express API 后端。每个进程在 dev 中有自己的端口,但在 Heroku 上部署只使用一个端口。

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

    "proxy": " 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'))
})
Run Code Online (Sandbox Code Playgroud)

  1. 使用以下内容编辑根目录的/package.json文件(请注意,使用 concurrently 包可以轻松地在本地运行整个应用程序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"
  },
Run Code Online (Sandbox Code Playgroud)

  1. 确保将所有后端包依赖项安装在根目录中,否则会出错。
  2. 确保你/Procfile有类似的东西web: node api/app.js

  • 添加 ENV 变量怎么样?我们应该在哪里做呢? (2认同)

mh-*_*bon 6

似乎您可以将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认同)

L. *_*yer 5

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

web: cd front && npm i && npm start
server: cd backend && npm i && npm start
Run Code Online (Sandbox Code Playgroud)

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