React.js多子域名配置求助:解决Invalid host header报错问题
在React中配置多子域名的解决方法
你遇到的Invalid host header错误,是因为React开发服务器默认会校验请求的Host头,未被纳入允许列表的域名会被拦截。以下是具体解决步骤:
1. 绑定本地子域名到localhost
先把自定义子域名指向本地IP(127.0.0.1),需要修改系统hosts文件:
- Windows系统:打开
C:\Windows\System32\drivers\etc\hosts(需管理员权限),添加一行:127.0.0.1 subdomain.localhost - Mac/Linux系统:打开终端执行命令编辑hosts文件:
同样添加上述内容后,按sudo nano /etc/hostsCtrl+O保存、Ctrl+X退出。
2. 配置React开发服务器允许子域名
根据你使用的React脚手架工具,选择对应配置方式:
若使用Create React App(CRA)
有两种简单配置方式:
- 方式一:修改启动命令
在项目package.json的scripts字段中,给start命令添加允许子域名的参数:
这里的"scripts": { "start": "react-scripts start --allowed-hosts .localhost", "build": "react-scripts build", "test": "react-scripts test" }.localhost表示允许所有*.localhost格式的子域名。 - 方式二:使用环境变量文件
在项目根目录创建.env.development文件,添加以下内容:ALLOWED_HOSTS=.localhost
若使用Vite
在项目根目录的vite.config.js中修改服务器配置:
import { defineConfig } from 'vite' import react from '@vitejs/plugin-react' export default defineConfig({ plugins: [react()], server: { host: '0.0.0.0', allowedHosts: ['.localhost'] } })
3. 验证配置
重启React开发服务器,访问subdomain.localhost:3000,此时应该能正常加载页面,不会再出现Invalid host header错误。
内容的提问来源于stack exchange,提问作者COders Lime
相关产品推荐
相关产品推荐

