输入或重定向到索引以外的任何路由时,Heroku 部署中出现 ENOENT 错误

ENOENT error in Heroku deployment when typing in or redirecting to any route other than index

我已阅读有关 Heroku 的 ENOENT 错误的其他主题,但他们在加载所有应用程序时遇到问题,我可以加载我的 SPA 中的每个页面,但我无法输入任何 URL 或重定向。

我有一个具有这种结构的 monorepo 项目(我使用 Brad Traversy 的 Proshop 项目作为模板,但我不得不降级到 Node.js 8.11.2 并从 ES 模块切换后端到常规的“require”语法。:

my-app/ 
├─ frontend/ 
├─ ├─ node_modules/ 
│  ├─ App.js 
├─ backend/ 
├─ ├─ node_modules/ 
│  ├─ server.js 
├─ .gitignore 
├─ package.json 
├─ README.md

这是快递服务路线的方式:

if (process.env.NODE_ENV === 'production') {
  app.use(express.static(path.join(__dirname, '../frontend/build')))

  app.get('*', (req, res) =>
    res.sendFile(path.resolve(__dirname, 'frontend', 'build', 'index.html'))
  )
} else {
  app.get('/', (req, res) => {
    res.send('API is running....')
  })
}

我的应用程序在开发环境中运行没有任何问题,但是当部署到 Heroku 时,索引路由有效,SPA 路由(由 react-router-dom 处理)有效,但如果用户键入任何 URL 或任何重定向发生我得到这个错误:

  "message": "ENOENT: no such file or directory, stat '/app/backend/frontend/build/index.html'",
  "stack": null

最可能的原因是什么?

我在 r/Heroku and u/jwsjr13 上问了这个问题,请您回答。问题基本上与 __dirname 如何自行解决有关。

Link to the answer.

直接引用:

https://nodejs.org/api/path.html#path_path_resolve_paths

If no path segments are passed, path.resolve() will return the absolute path of the current working directory.

看来是相对路径问题。 __dirname 是全局的 Node 8 必须出现的变量。

您的开发环境有效但生产环境无效的原因 这是:

在开发中,您可能使用了一个 NPM 包并发调用 运行 两个 进程:一个开发版本的反应与 api 代理到 第二个进程:你的节点服务器。他们会 运行 在两个不同的 端口和你的 API 来自你的反应应用程序的请求将代理到你的 快递服务器。

在 prod 上,react 实际上被编译为 HTML/CSS/JS 并被放置 进入 frontend/build/ 目录。现在您的应用 运行 合二为一 处理服务器抛出任何已编译的 React 应用程序 未被上述 API 路由捕获的请求。