首页 > 解决方案 > 如何将服务器(Express - MERN)移动到子目录并在 Heroku 上工作

问题描述

我有一个 MERN 堆栈项目,以前与服务器相关的所有内容都位于根级别,但是 ESLINT、VSCODE 和 package.json 文件的问题意味着我将与服务器相关的所有内容移动到它自己的子目录中。

然而,这意味着 Heroku 现在给我的错误看起来与 Express 无法提供文件有关。请参阅下面 Heroku 日志中的错误截图。

在 Heroku 上部署应用程序工作正常,没有构建错误。

在此处输入图像描述

我的 server.js 文件中如何配置 Express

// prod only, uses /public in dev env
app.use(express.static('index.html', { root: '../client/build' }) );

app.get('*', (req, res) => {
    res.sendFile(`index.html`, { root: '../client/build' });
});

我的目录结构

client/
   src/
   public/
   build/
   package.json
server/
   routes/
   models/
   server.js
   package.json
.gitignore
README.md
package.json // very small file only including scripts to satisfy Heroku

根级 package.json(文件的全部内容)

{
"scripts": {
    "start": "cd server && node server.js",
    "build": "cd client && npm run build",
    "install-server": "cd server && npm install",
    "install-client": "cd client && npm install",
    "heroku-postbuild": "npm run install-server && npm run install-client && npm run build"
    }
}

笔记:

  1. 当我在本地启动项目时,Express 在提供文件时没有问题
  2. 如果您使用的是 Node.js 类型的项目,Heroku 需要根目录下的 package.json 文件。这就是为什么我的根目录中有一个小 package.json 里面没有太多内容的原因

标签: javascriptexpressherokumern

解决方案


事实证明,从此切换:

app.use(express.static('index.html', { root: '../client/build' }) );

app.use(express.static('/app/client/build'))

解决了这个问题。

我确实尝试app.use(express.static('index.html', { root: '/app/client/build' }) );过,但这再次破坏了网站。


推荐阅读