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

Express.js应用使用Axios调用GitHub API获取数据失败排查

问题:Express.js中Axios调用GitHub API报socket hang up错误

现象

  • 通过curl命令可正常获取GitHub API数据,但使用Axios发起相同请求时,抛出socket hang up(错误码ECONNRESET)
  • 应用运行在需要代理的VDI环境中,已为Axios配置与curl一致的代理参数

可用的curl命令

curl -L -H "Accept: application/vnd.github+json" -H "Authorization: Bearer github_pat_******" -H "X-GitHub-Api-Version: 2022-11-28" "https://api.github.com/repos/ionutdr23/test-githubapi/commits?since=2024-10-01T00:00:00.000Z"

Axios实例配置代码

let axiosConfig: {
  baseURL: string;
  timeout: number;
  headers: {
    Authorization: string;
    Accept: string;
  };
  proxy?: {
    protocol: string;
    host: string;
    port: number;
  };
  httpsAgent?: https.Agent;
  httpAgent?: http.Agent;
} = {
  baseURL: GITHUB_API_URL,
  timeout: 5000,
  headers: {
    Authorization: `Bearer ${GITHUB_TOKEN}`,
    Accept: "application/vnd.github.v3+json",
  },
  httpsAgent: new https.Agent({keepAlive: true}),
  httpAgent: new http.Agent({keepAlive: true}),
};

if (process.env.ENABLE_PROXY === "true") {
  axiosConfig = { 
    ...axiosConfig,
    proxy: {
      protocol: "http",
      host: "${PROXY_SERVER}",
      port: PROXY_PORT,
    },
  };
}

const axiosInstance = axios.create(axiosConfig);

Axios调用代码

const commitsUrl = `/repos/${REPO_OWNER}/${REPO_NAME}/commits?since=${since}`;
const response = await axiosInstance.get(commitsUrl);

完整错误信息

Error fetching file changes: AxiosError: socket hang up
    at Function.AxiosError.from (/home/cdragomi/test-githubapi/express-ts-app/node_modules/axios/lib/core/AxiosError.js:92:14)
    at RedirectableRequest.handleRequestError (/home/cdragomi/test-githubapi/express-ts-app/node_modules/axios/lib/adapters/http.js:620:25)
    at RedirectableRequest.emit (node:events:532:35)
    at RedirectableRequest.emit (node:domain:488:12)
    at ClientRequest.eventHandlers.<computed> (/home/cdragomi/test-githubapi/express-ts-app/node_modules/follow-redirects/index.js:49:24)
    at ClientRequest.emit (node:events:520:28)
    at ClientRequest.emit (node:domain:488:12)
    at Socket.socketOnEnd (node:_http_client:526:9)
    at Socket.emit (node:events:532:35)
    at Socket.emit (node:domain:488:12)
    at Axios.request (/home/cdragomi/test-githubapi/express-ts-app/node_modules/axios/lib/core/Axios.js:45:41)
    at processTicksAndRejections (node:internal/process/task_queues:95:5)
    at async getFileChangesSinceDate (/home/cdragomi/test-githubapi/express-ts-app/src/services/githubService.ts:65:22)
    at async fetchFileChangesSinceDate (/home/cdragomi/test-githubapi/express-ts-app/src/controllers/commitController.ts:25:25) {
  code: 'ECONNRESET',
  config: {
    transitional: {
      silentJSONParsing: true,
      forcedJSONParsing: true,
      clarifyTimeoutError: false
    },
    adapter: [ 'xhr', 'http', 'fetch' ],
    transformRequest: [ [Function: transformRequest] ],
    transformResponse: [ [Function: transformResponse] ],
    timeout: 5000,
    xsrfCookieName: 'XSRF-TOKEN',
    xsrfHeaderName: 'X-XSRF-TOKEN',
    maxContentLength: -1,
    maxBodyLength: -1,
    env: { FormData: [Function], Blob: [class Blob] },
    validateStatus: [Function: validateStatus],
    headers: Object [AxiosHeaders] {
      Accept: 'application/vnd.github.v3+json',
      'Content-Type': undefined,
      Authorization: 'Bearer github_pat_***********************',
      'User-Agent': 'axios/1.7.7',
      'Accept-Encoding': 'gzip, compress, deflate, br'
    },
    baseURL: 'https://api.github.com',
    proxy: { protocol: 'http', host: 'proxy******', port: **** },
    method: 'get',
    url: '/repos/ionutdr23/test-githubapi/commits?since=2024-10-21T00:00:00.000Z',
    data: undefined
  },
  request: <ref *1> Writable {
    _events: {
      close: undefined,
      error: [Function: handleRequestError],
      prefinish: undefined,
      finish: undefined,
      drain: undefined,
      response: [Function: handleResponse],
      socket: [Array],
      timeout: undefined,
      abort: undefined
    },
    _writableState: WritableState {
      highWaterMark: 65536,
      length: 0,
      corked: 0,
      onwrite: [Function: bound onwrite],
      writelen: 0,
      bufferedIndex: 0,
      pendingcb: 0,
      [Symbol(kState)]: 17580812,
      [Symbol(kBufferedValue)]: null
    },
    _maxListeners: undefined,
    _options: {
      maxRedirects: 21,
      maxBodyLength: Infinity,
      protocol: 'http:',
      path: 'https://api.github.com/repos/ionutdr23/test-githubapi/commits?since=2024-10-21T00:00:00.000Z',
      method: 'GET',
      headers: [Object: null prototype],
      agents: [Object],
      auth: undefined,
      family: undefined,
      beforeRedirect: [Function: dispatchBeforeRedirect],
      beforeRedirects: [Object],
      hostname: 'proxy******',
      port: ****,
      agent: undefined,
      nativeProtocols: [Object],
      pathname: 'https://api.github.com/repos/ionutdr23/test-githubapi/commits',
      search: '?since=2024-10-21T00:00:00.000Z'
    },
    _ended: true,
    _ending: true,
    _redirectCount: 0,
    _redirects: [],
    _requestBodyLength: 0,
    _requestBodyBuffers: [],
    _eventsCount: 3,
    _onNativeResponse: [Function (anonymous)],
    _currentRequest: ClientRequest {
      _events: [Object: null prototype],
      _eventsCount: 7,
      _maxListeners: undefined,
      outputData: [],
      outputSize: 0,
      writable: true,
      destroyed: false,
      _last: true,
      chunkedEncoding: false,
      shouldKeepAlive: true,
      maxRequestsOnConnectionReached: false,
      _defaultKeepAlive: true,
      useChunkedEncodingByDefault: false,
      sendDate: false,
      _removedConnection: false,
      _removedContLen: false,
      _removedTE: false,
      strictContentLength: false,
      _contentLength: 0,
      _hasBody: true,
      _trailer: '',
      finished: true,
      _headerSent: true,
      _closed: false,
      _header: 'GET https://api.github.com/repos/ionutdr23/test-githubapi/commits?since=2024-10-21T00:00:00.000Z HTTP/1.1\r\n' +
        'Accept: application/vnd.github.v3+json\r\n' +
        'Authorization: Bearer github_pat_***********************\r\n' +
        'User-Agent: axios/1.7.7\r\n' +
        'Accept-Encoding: gzip, compress, deflate, br\r\n' +
        'host: api.github.com\r\n' +
        'Connection: keep-alive\r\n' +
        '\r\n',
      _keepAliveTimeout: 0,
      _onPendingData: [Function: nop],
      agent: [Agent],
      socketPath: undefined,
      method: 'GET',
      maxHeaderSize: undefined,
      insecureHTTPParser: undefined,
      joinDuplicateHeaders: undefined,
      path: 'https://api.github.com/repos/ionutdr23/test-githubapi/commits?since=2024-10-21T00:00:00.000Z',
      _ended: false,
      res: null,
      aborted: false,
      timeoutCb: [Function: emitRequestTimeout],
      upgradeOrConnect: false,
      parser: null,
      maxHeadersCount: null,
      reusedSocket: false,
      host: 'proxy******',
      protocol: 'http:',
      _redirectable: [Circular *1],
      [Symbol(shapeMode)]: false,
      [Symbol(kCapture)]: false,
      [Symbol(kBytesWritten)]: 0,
      [Symbol(kNeedDrain)]: false,
      [Symbol(corked)]: 0,
      [Symbol(kChunkedBuffer)]: [],
      [Symbol(kChunkedLength)]: 0,
      [Symbol(kSocket)]: [Socket],
      [Symbol(kOutHeaders)]: [Object: null prototype],
      [Symbol(errored)]: null,
      [Symbol(kHighWaterMark)]: 65536,
      [Symbol(kRejectNonStandardBodyWrites)]: false,
      [Symbol(kUniqueHeaders)]: null
    },
    _currentUrl: 'https://api.github.com/repos/ionutdr23/test-githubapi/commits?since=2024-10-21T00:00:00.000Z',
    _timeout: null,
    [Symbol(shapeMode)]: true,
    [Symbol(kCapture)]: false
  },
  cause: Error: socket hang up
      at Socket.socketOnEnd (node:_http_client:526:23)
      at Socket.emit (node:events:532:35)
      at Socket.emit (node:domain:488:12)
      at endReadableNT (node:internal/streams/readable:1696:12)
      at processTicksAndRejections (node:internal/process/task_queues:82:21) {
    code: 'ECONNRESET'
  }
}
ERROR: Error fetching file changes:
GET /file-changes?since=2024-10-21T00:00:00.000Z 500 35.768 ms - 41

解决方案

将Axios替换为node-fetch后,请求可正常完成。遇到相同问题可尝试此替换方案。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 16:30:54