You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

http-proxy模块配合create-react-app启动失败,serve -s build可正常运行

问题解决:代理服务器连接create-react-app端口失败(ECONNREFUSED ::1:3000)

问题原因

  1. IPv6/IPv4监听不匹配:create-react-app默认仅监听IPv4的127.0.0.1地址,代理服务器使用localhost时,系统可能优先解析为IPv6的::1,导致连接被拒绝。
  2. 代理错误事件重复绑定:当前代码在每个请求处理函数内绑定proxy.on('error'),会导致同一错误被多次触发处理,引发异常。

解决方案

方案1:强制代理使用IPv4连接React服务

将代理代码中的guiUrl从http://localhost:3000改为http://127.0.0.1:3000,直接指定IPv4地址:

const guiUrl = 'http://127.0.0.1:3000'; // 改用IPv4地址避免解析到IPv6

方案2:让create-react-app监听IPv6地址

修改React项目的package.json中的启动脚本,强制服务监听IPv6的::地址:

  • Linux/macOS:
    "scripts": {
      "start": "HOST=:: react-scripts start"
    }
    
  • Windows:
    "scripts": {
      "start": "set HOST=:: && react-scripts start"
    }
    

修复代理错误事件绑定

将proxy.on('error')的绑定移到HTTP服务器创建的外部,确保只绑定一次:

修改后的完整代理代码:

const httpProxy = require('http-proxy');
const http = require('http');
const { maintenanceHtml } = require('./maintenanceHtml');

const proxy = httpProxy.createServer();

const guiUrl = 'http://127.0.0.1:3000'; // react frontend app
const apiUrl = 'http://localhost:4000'; // 1st api server
const apiPrefix = '/api';
const fnApiUrl = 'http://localhost:1000'; // 2nd api server
const fnApiPrefix = '/secondapi';
const port = 80;

// 只绑定一次错误事件
proxy.on('error', (error, req, res) => {
  console.log(error.message);
  res.end(maintenanceHtml);
});

http.createServer((req, res) => {
  let target = guiUrl;
  if (req.url.startsWith(apiPrefix)) {
    req.url = req.url.replace(apiPrefix, '/');
    target = apiUrl;
  }
  if (req.url.startsWith(fnApiPrefix)) {
    req.url = req.url.replace(fnApiPrefix, '/');
    target = fnApiUrl;
  }
  proxy.web(req, res, { target });
}).listen(port, () => {
  console.log(`Proxy server has started on port 80`);
});

验证

  1. 重启代理服务器
  2. 用npm start启动React项目
  3. 访问localhost:80,即可正常加载React前端,同时/api和/secondapi的转发不受影响。

内容的提问来源于stack exchange,提问作者Alexander 2049

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 04:55:28