javascript - 如何将服务器(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"
}
}
笔记:
- 当我在本地启动项目时,Express 在提供文件时没有问题
- 如果您使用的是 Node.js 类型的项目,Heroku 需要根目录下的 package.json 文件。这就是为什么我的根目录中有一个小 package.json 里面没有太多内容的原因
解决方案
事实证明,从此切换:
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' }) );
过,但这再次破坏了网站。
推荐阅读
- c# - Abstract Generic Mocking - 不能实例化属性的代理类?
- docker - 使用 GitHub Actions 构建 Docker 映像的问题
- junit - Robolectric 4.4 单元测试错误 - 主循环器已将未执行的可运行文件排队
- javascript - 如何使用节点 sdk 检查容器是否存在于 cosmos DB 中?
- wso2 - WSO2 - 3.2.0 - Docker - 创建 API - 连接错误
- kubernetes - 当 Pod 通常需要低 CPU 但会定期扩展时,如何使用 K8S HPA 和 autoscaler
- angular - 在我的角度项目中设置规则'max-classes-per-file'。ESLint 触发的错误是“文件有太多类”
- c++11 - 使用类型推导向下转换为子类的方法
- java - 如何确保随机产生的值在 Java 中是唯一的
- react-native - 如何使用 reanimated v2 更改背景颜色与过渡