Heroku 部署 React-Express App 后出现 Invalid Host Header
结论
Invalid Host Header 是 react-scripts start 启动的 webpack 开发服务器返回的。当前 Heroku 的 npm start 会同时启动 React 开发服务器和 Express:
concurrently "npm run server" "npm run client"
Heroku 只会把外部请求转发到当前 Web Dyno 的 $PORT。从日志看,React 开发服务器占用了这个动态端口,Express 却固定监听 5000。访问 Heroku 域名时,请求因此进入 webpack 开发服务器,随后被 Host 校验拒绝。
生产环境应在部署阶段构建 React,运行时只启动 Express。Express 需要监听 process.env.PORT,并提供 client/build 中的静态文件。/api 路由要注册在 React 的通配路由之前。
修改 server.js
将 server.js 改为:
const path = require('path');
const _ = require('lodash');
const express = require('express');
const app = express();
const port = process.env.PORT || 5000;
const listOfTexts = [
'Logic will get you from A to B. Imagination will take you everywhere.',
"There are 10 kinds of people. Those who know binary and those who don't.",
'There are two ways of constructing a software design. One way is to make it ' +
'so simple that there are obviously no deficiencies and the other is to make ' +
'it so complicated that there are no obvious deficiencies.',
"It's not that I'm so smart, it's just that I stay with problems longer.",
'It is pitch dark. You are likely to be eaten by a grue.',
];
// API 路由必须放在 React 通配路由之前
app.get('/api', (req, res) => {
res.send(_.sample(listOfTexts));
});
if (process.env.NODE_ENV === 'production') {
const buildPath = path.join(__dirname, 'client', 'build');
app.use(express.static(buildPath));
// Express 4 的 SPA fallback
app.get('*', (req, res) => {
res.sendFile(path.join(buildPath, 'index.html'));
});
}
app.listen(port, '0.0.0.0', () => {
console.log(`Server is running on port ${port}`);
});
原代码将端口固定成了 5000:
const port = 5000;
Heroku 会在运行时分配端口,并通过 process.env.PORT 传给应用。Web 进程必须监听这个端口,Heroku Router 才能把请求交给 Express。
原来的 app.get('*') 还写在了 /api 前面。生产环境中,/api 会先匹配 *,返回 React 的 index.html,后面的 API 处理函数也就不会执行。
当前依赖版本是 express@^4.18.2,因此这里采用 Express 4 的写法。如果以后升级到 Express 5,需要按照 Express 5 的路由语法修改通配路由。
修改根目录的 package.json
生产环境中的 start 只负责启动 Express。React 开发服务器和 nodemon 继续用于本地开发:
{
"name": "workshop01",
"version": "1.0.0",
"scripts": {
"start": "node server.js",
"server": "nodemon server.js",
"client": "npm start --prefix client",
"dev": "concurrently \"npm run server\" \"npm run client\"",
"heroku-postbuild": "npm install --prefix client && npm run build --prefix client",
"test": "echo \"Error: no test specified\" && exit 1"
},
"dependencies": {
"express": "^4.18.2",
"lodash": "^4.17.21"
},
"devDependencies": {
"concurrently": "^8.2.1",
"nodemon": "^3.0.1"
}
}
如果 client/package.json 将 react-scripts 放在 devDependencies 中,而部署环境会在构建前裁剪开发依赖,可以使用:
"heroku-postbuild": "npm install --prefix client --include=dev && npm run build --prefix client"
如果项目中有有效的 client/package-lock.json,还可以将 npm install 换成 npm ci:
"heroku-postbuild": "npm ci --prefix client --include=dev && npm run build --prefix client"
正确的文件名是 package-lock.json。如果问题中的 package.lock.json 不是展示时的笔误,需要改正。
本地开发配置
本地仍然可以同时运行两个开发进程:
npm run dev
React 开发服务器和 Express 此时使用不同的端口。要让本地的 fetch('/api') 转发到 Express,可以在 client/package.json 中加入:
{
"proxy": "http://localhost:5000"
}
proxy 只用于本地开发。部署后,React 静态文件和 /api 都由同一个 Express 应用提供,所以现有代码仍可使用相对地址:
fetch('/api')
部署时的实际流程
修改后的 Heroku 运行流程如下:
部署阶段:
npm install
heroku-postbuild
└── 构建 client/build
运行阶段:
npm start
└── node server.js
├── GET /api -> Express API
└── 其他请求 -> client/build
Heroku 的 Web Dyno 中不应再执行:
react-scripts start
也不建议设置 DANGEROUSLY_DISABLE_HOST_CHECK=true 来关闭 webpack 的 Host 校验。这会掩盖当前的部署问题,并降低开发服务器的安全性。生产环境并不需要启动这个开发服务器。
如何确认修改生效
重新部署后,日志中应该出现类似内容:
Starting process with command `npm start`
> node server.js
Server is running on port 12345
这个端口由 Heroku 分配,每次启动时都可能不同。日志中不应再出现:
Starting the development server...
Local: http://localhost:...
webpack compiled successfully
接着分别访问:
https://你的应用域名/
https://你的应用域名/api
第一个地址应返回 React 页面,第二个地址应返回一条随机文本。
日志末尾的 Process exited with status 143 表示进程收到了 SIGTERM。Dyno 停止、重启或重新部署时都可能出现这条记录,仅凭这段日志无法判断具体原因。它与 Invalid Host Header 没有直接关系。Babel 和 webpack 的弃用警告也不是这次页面错误的原因,可以等应用恢复运行后再处理。
备注:内容仅供参考。
