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

如何修复Axios 1.6中的AxiosError: socket hang up错误?

解决Axios 1.6 GET请求出现socket hang up错误的方案

我使用Axios 1.6发送GET请求,代码如下:

try {
  const response = await axios({
    method: "get",
    url,
    responseType: "stream",
  });
} catch (err) {
  console.log(err)
}

该请求此前可正常运行,但现在出现如下错误:

AxiosError: socket hang up at AxiosError.from...

我尝试添加了部分配置选项,但问题仍未解决:

const response = await axios({
  method: "get",
  url,
  responseType: "stream",
  proxy: false,
  httpsAgent: new https.Agent({
    keepAlive: true
  }),
  timeout: 60000,
});

以下是几个可行的修复方向:

  • 检查目标服务状态:先确认请求的目标服务器是否正常运行,有没有重启、限流或者网络策略变更——socket hang up多数情况是服务端主动断开了连接。
  • 细化keepAlive配置:给httpsAgent补充更多参数,避免连接复用异常:
const httpsAgent = new https.Agent({
  keepAlive: true,
  maxSockets: 10, // 根据你的并发需求调整
  keepAliveMsecs: 30000, // 连接保持时长,单位毫秒
});
  • 必须消费流式响应:因为设置了responseType: "stream",如果拿到响应后不及时处理流数据,服务端会因超时断开连接。务必在获取response后立刻处理流:
try {
  const response = await axios({
    method: "get",
    url,
    responseType: "stream",
    proxy: false,
    httpsAgent: new https.Agent({ keepAlive: true }),
    timeout: 60000,
  });
  // 必须处理流,否则会触发socket hang up
  response.data.on('data', chunk => {
    // 这里写数据块的处理逻辑,比如写入文件或解析内容
  });
  response.data.on('end', () => {
    console.log('流处理完成');
  });
  response.data.on('error', (streamErr) => {
    console.error('流处理出错:', streamErr);
  });
} catch (err) {
  console.log(err);
}
  • 强制使用HTTP/1.1:如果目标服务对HTTP/2支持有问题,强制Axios使用HTTP/1.1协议:
const httpsAgent = new https.Agent({
  keepAlive: true,
  maxVersion: 'TLSv1.2', // 匹配服务端支持的TLS版本
});
  • 排查网络中间件:检查是否存在系统层面的代理、防火墙或CDN限制,临时切换网络环境测试是否能恢复正常。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 10:01:09