Ubuntu/Debian下使用Axios调用API出现socket hang up(ECONNRESET)错误但Windows正常
Ubuntu/Debian下使用Axios调用API出现socket hang up(ECONNRESET)错误但Windows正常
遇到这种跨平台的网络问题确实挺闹心的,我来帮你梳理下可能的原因和解决方向:
首先明确你的问题场景:这个错误只出现在Ubuntu 24.04和Debian 12系统中,使用Axios调用API时反复触发socket hang up错误(对应错误码ECONNRESET),但在Windows环境下完全正常运行。你遇到的具体错误栈如下:
cause: Error: socket hang up at connResetException (node:internal/errors:720:14) at TLSSocket.socketOnEnd (node:_http_client:525:23) at TLSSocket.emit (node:events:529:35) at endReadableNT (node:internal/streams/readable:1400:12) at process.processTicksAndRejections (node:internal/process/task_queues:82:21) { code: 'ECONNRESET' }
下面是几个针对性的排查和解决建议:
检查TLS/SSL协议兼容性:Ubuntu 24.04和Debian 12默认启用了更严格的TLS配置,而目标API服务器可能不支持最新的TLS版本。你可以尝试强制Axios使用兼容的TLS协议(比如TLSv1.2):
const https = require('https'); const axios = require('axios'); const tlsAgent = new https.Agent({ secureProtocol: 'TLSv1_2_method' }); axios.get('你的API接口地址', { httpsAgent: tlsAgent }) .then(res => console.log(res.data)) .catch(err => console.error(err));模拟Windows请求头:部分API服务器会根据客户端的User-Agent做限制,Linux下默认的Node.js请求头可能被服务器拦截。你可以修改Axios的请求头,模拟Windows浏览器的User-Agent:
axios.get('你的API接口地址', { headers: { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36' } })调整网络连接配置:Linux下的Node.js网络模块在长连接、超时处理上和Windows有细微差异,你可以尝试开启
keepAlive并延长超时时间:const https = require('https'); const axios = require('axios'); const keepAliveAgent = new https.Agent({ keepAlive: true, timeout: 60000 // 设置60秒超时 }); axios.get('你的API接口地址', { httpsAgent: keepAliveAgent })排查系统网络限制:检查Ubuntu/Debian系统的防火墙(ufw)、iptables规则,或者是否有全局代理设置拦截了请求。可以临时关闭防火墙测试,确认是否是系统层面的限制导致的。
备注:内容来源于stack exchange,提问作者yechale degu




