react如何设置host
设置 React 应用的 Host
在 React 项目中设置 host 通常涉及开发服务器或生产环境的配置。以下是几种常见场景的配置方法:
开发环境(React 开发服务器)
修改 package.json 中的 scripts 部分,通过 HOST 环境变量指定:
"scripts": {
"start": "HOST=0.0.0.0 react-scripts start"
}
Windows 用户需使用 set 命令:

"start": "set HOST=0.0.0.0 && react-scripts start"
使用 .env 文件配置
在项目根目录创建 .env 文件并添加:
HOST=0.0.0.0
此配置会应用于 react-scripts start 启动的开发服务器。

生产环境(Web 服务器配置)
生产环境中 host 通常由 Web 服务器(如 Nginx、Apache)控制。以 Nginx 为例的配置片段:
server {
listen 80;
server_name your-domain.com;
location / {
root /path/to/react/build;
try_files $uri /index.html;
}
}
自定义开发服务器配置
如需更高级配置,可 eject 项目后修改 webpackDevServer.config.js(不推荐 eject):
module.exports = {
host: '0.0.0.0',
port: 3000
};
Docker 容器部署
在 Docker 中运行时,需同时配置容器和 React 应用:
EXPOSE 3000
CMD ["npm", "start", "--", "--host", "0.0.0.0"]






