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

Node.js升级至22后调用Meta Graph API遇Axios AggregateError [ETIMEDOUT]求助

解决Node.js 22升级后调用Meta Graph API的Axios ETIMEDOUT错误

核心问题分析

你遇到的ENETUNREACH错误指向IPv6网络连通性问题,Node.js 22默认优先使用IPv6解析域名,若环境IPv6路由存在间歇性故障,就会触发超时。以下是针对性解决方案:


1. 调整Node.js IP解析优先级

Node.js 18+默认启用IPv6优先解析,可通过两种方式强制优先IPv4:

  • 环境变量配置:启动应用时添加参数
    NODE_OPTIONS="--dns-result-order=ipv4first" node your-app.js
    
  • 代码层面强制IPv4解析:
    const dns = require('dns');
    // 全局设置DNS解析优先返回IPv4
    dns.setDefaultResultOrder('ipv4first');
    

2. 优化Axios连接策略

升级Node.js后,HTTP连接池和超时逻辑可能变化,需显式配置:

  • 自定义HTTP/HTTPS代理与连接池:
    const axios = require('axios');
    const http = require('http');
    const https = require('https');
    
    const apiClient = axios.create({
      baseURL: 'https://graph.facebook.com/v19.0',
      timeout: 15000, // 延长超时至15秒
      httpAgent: new http.Agent({ 
        keepAlive: true, // 启用长连接
        maxSockets: 15  // 调整最大并发连接数
      }),
      httpsAgent: new https.Agent({ 
        keepAlive: true,
        maxSockets: 15
      })
    });
    
  • 添加自动重试逻辑:使用axios-retry处理网络错误
    先安装依赖:
    npm install axios-retry
    
    配置重试:
    const axiosRetry = require('axios-retry');
    
    axiosRetry(apiClient, {
      retries: 3, // 最多重试3次
      retryDelay: axiosRetry.exponentialDelay, // 指数退避延迟
      retryCondition: (error) => {
        // 仅重试网络超时或不可达错误
        return axiosRetry.isNetworkError(error) || error.code === 'ETIMEDOUT';
      }
    });
    

3. 验证环境IPv6稳定性

即使启用了IPv6出站,云环境的IPv6路由可能存在间歇性故障:

  • 在应用服务器上定期测试连通性:
    # 测试IPv6 ping
    ping6 2a03:2880:f042:12:face:b00c:0:2 -c 5
    # 测试IPv6下的API请求
    curl -6 https://graph.facebook.com/v19.0/me --connect-timeout 5
    
  • 联系云服务商确认区域IPv6网络状态,排查是否存在路由波动

4. Meta API端优化

  • 使用批量请求减少单次连接次数,降低超时概率:
    // 示例批量请求
    apiClient.post('/', {
      batch: [
        { method: 'POST', relative_url: `${id1}/messages`, body: JSON.stringify({...}) },
        { method: 'POST', relative_url: `${id2}/messages`, body: JSON.stringify({...}) }
      ],
      access_token: 'YOUR_ACCESS_TOKEN'
    });
    
  • 确认使用的API版本(v19.0)为Meta当前稳定版,避免版本兼容问题

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 03:15:06