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

基于http-proxy-middleware的代理配置,周期性出现ECONNRESET错误

问题排查与解决方案

1. 禁用axios连接池,强制每次请求新建连接

默认axios会复用连接,闲置过久的连接被Naver端主动关闭后,复用失效连接就会触发ECONNRESET错误。可以在后端请求Naver Cafe接口时,配置专属Agent禁用连接复用:

const axios = require('axios');
const http = require('http');
const https = require('https');

// 创建不复用连接的Agent实例
const httpAgent = new http.Agent({ keepAlive: false });
const httpsAgent = new https.Agent({ keepAlive: false });

// 请求时指定Agent
axios.get('https://目标Naver-Cafe接口地址', {
  httpAgent,
  httpsAgent
})

2. 给后端请求添加针对性重试机制

闲置后首次请求大概率是因为连接已失效,添加重试逻辑自动恢复:

const axiosRetry = require('axios-retry');

// 配置仅针对ECONNRESET错误重试
axiosRetry(axios, {
  retries: 3,
  retryDelay: (count) => count * 1000, // 每次重试间隔递增1秒
  retryCondition: (error) => error.code === 'ECONNRESET'
});

3. 调整前端代理的连接配置

前端http-proxy-middleware可能存在闲置连接未及时清理的问题,在代理配置中添加超时并禁用连接复用:

const { createProxyMiddleware } = require('http-proxy-middleware');

app.use('/api', createProxyMiddleware({
  target: 'http://localhost:3001',
  changeOrigin: true,
  proxyTimeout: 5000, // 代理请求超时时间
  timeout: 5000, // 连接超时时间
  onProxyReq: (proxyReq) => {
    proxyReq.setHeader('Connection', 'close'); // 强制关闭连接,不复用
  }
}));

4. 后端定期发送心跳请求(可选)

如果需要维持与Naver端的连接,可以定时发送轻量请求避免连接被回收:

// 每5分钟发送一次心跳请求
setInterval(async () => {
  try {
    await axios.get('https://cafe.naver.com', { timeout: 1000 });
  } catch (err) {
    // 心跳失败无需处理,下次自动重试
  }
}, 5 * 60 * 1000);

5. 升级axios版本

Node.js 18.x搭配旧版axios可能存在连接池兼容性问题,升级到最新稳定版:

npm update axios

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 16:15:27