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

Node.js中API内部调用时出现socket hang up错误求助

Fixing "socket hang up" Error When Calling APIs from Node.js

Hey there, let's break down that socket hang up error you're facing when calling one API from another in Node.js. This is a super common issue with a handful of straightforward fixes—here's what you need to know:

Common Causes & Solutions

1. Target API Timed Out or Closed the Connection Early

This is the most frequent culprit. The API you're calling might be taking too long to respond, or it's dropping the connection before sending a full response.

Fix:
Set explicit timeouts for your requests to avoid hanging indefinitely. Here's how to do it with Node's built-in http module and with axios:

Using http module:

const http = require('http');

const requestOptions = {
  hostname: 'your-target-api.com',
  path: '/your-endpoint',
  method: 'POST',
  timeout: 10000, // 10-second timeout
  headers: {
    'Content-Type': 'application/json'
  }
};

const req = http.request(requestOptions, (res) => {
  // Make sure to consume the response stream (even if you don't need the data)
  res.on('data', () => {});
  res.on('end', () => {
    console.log('Request completed successfully');
  });
});

// Handle timeout event
req.on('timeout', () => {
  req.abort();
  console.error('Request timed out—target API took too long to respond');
});

// Handle errors
req.on('error', (err) => {
  if (err.code === 'ECONNRESET') {
    console.error('Connection reset by target API—likely a timeout or server issue');
  } else {
    console.error('Request error:', err.message);
  }
});

// Send the request body if needed
req.write(JSON.stringify({ key: 'value' }));
req.end();

Using axios:

const axios = require('axios');

axios.post('https://your-target-api.com/your-endpoint', { key: 'value' }, {
  timeout: 10000, // 10-second timeout
  headers: {
    'Content-Type': 'application/json'
  }
})
.then(response => {
  console.log('Response:', response.data);
})
.catch(error => {
  if (error.code === 'ECONNABORTED') {
    console.error('Request timed out');
  } else if (error.code === 'ECONNRESET') {
    console.error('Connection reset by target API');
  } else {
    console.error('Request failed:', error.message);
  }
});

2. Missing or Incorrect Request Headers

Sometimes the target API expects specific headers (like Authorization, Accept, or Content-Type) that you're not sending. If the API rejects the request early, it can trigger a socket hang up.

Fix:
Compare your Node.js request headers to a working request (e.g., from Postman or curl). Make sure all required headers are included and formatted correctly.

3. Exceeding Node.js's Default Connection Limit

Node.js's http module has a default limit of 5 concurrent connections per host. If you're making multiple parallel API calls, this can cause connections to hang.

Fix:
Increase the max sockets limit globally, or use a custom Agent for your requests:

const http = require('http');

// Increase global max sockets
http.globalAgent.maxSockets = 20;

// Or use a custom Agent for specific requests
const customAgent = new http.Agent({ maxSockets: 20 });

const requestOptions = {
  hostname: 'your-target-api.com',
  path: '/your-endpoint',
  method: 'GET',
  agent: customAgent
};

4. Not Consuming the Response Stream

If you don't listen to the data event of the response stream, Node.js might keep the connection open, leading to a hang up error.

Fix:
Even if you don't need the response data, add a listener for the data event to consume the stream (like in the http module example above).

Quick Troubleshooting Steps

  • Test the target API directly with Postman/curl to confirm it's working as expected.
  • Check the target API's server logs to see if it's throwing errors when receiving your request.
  • If using HTTPS, verify that your Node.js environment trusts the API's SSL certificate (though this usually throws a different error).

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 04:18:33