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

Node.js中Socket hang up错误:调用getPrologFarm2接口失败排查

Socket Hang Up Error When Calling getPrologFarm2 in Node.js (Works with getFarmacias)

Let’s break down why you’re seeing this "socket hang up" error and fix it—your code has a couple of critical async handling issues that are causing the problem, even though getFarmacias seems to work (that’s probably just luck, not good code!).

Why the "Socket Hang Up" Happens

This error usually pops up when:

  1. The Prolog service’s getPrologFarm2 endpoint isn’t responding in time, or closes the connection unexpectedly.
  2. Your Node.js code ends the HTTP response to your client before the getPrologFarm2 call finishes, which cuts off the ongoing request to the Prolog service mid-process.

Looking at your code, the second issue is definitely at play here. Let’s walk through the problems:

Issue 1: You’re Not Waiting for getPrologFarm2 to Complete

Right now, your code does this:

var info1;
client.methods.getPrologFarm2(function (data, res) {
  info1 = data
});
res.json(info1); // This runs BEFORE the callback fires!

Since getPrologFarm2 is asynchronous (just like getFarmacias), the callback won’t run until the API call is done. But you’re immediately sending res.json(info1)—which is still undefined at that point. This ends the response to your client, and Node.js might kill the socket connection to the Prolog service while it’s still trying to respond, causing the "socket hang up" error.

Issue 2: Your getFarmacias Code is a Tickling Time Bomb

You’re using sleep(2000) to "wait" for the getFarmacias callback, which is a terrible practice in Node.js. Blocking the event loop with synchronous sleep can tank performance, and it only works if the getFarmacias call happens to finish within 2 seconds. If the API ever takes longer (e.g., during high load), your code will break.

Fixing the Code Properly

Let’s rewrite this using proper async patterns (we’ll stick with nested callbacks since that’s what your current code uses—you can switch to Promises/async/await later for cleaner code):

router.route('/farmacias')
.get(function (req, res) {
  // First, wait for getFarmacias to return data
  client.methods.getFarmacias(function (farmaciasData) {
    var hours = new Date().getHours();
    var list = [];
    // Note: I changed i=1 to i=0—if you meant to skip the first item, keep i=1 and add a comment!
    for (var i = 0; i < farmaciasData.length; i++) {
      if (hours < 12) {
        if (farmaciasData[i].restricaoTemporal === 'manha') {
          list.push(farmaciasData[i].nome);
        }
      } else {
        if (farmaciasData[i].restricaoTemporal === 'tarde') {
          list.push(farmaciasData[i].nome);
        }
      }
    }

    // Now call getPrologFarm2 ONLY after getFarmacias is done
    client.methods.getPrologFarm2(function(prologData) {
      // Send the response once we have the Prolog data
      res.json(prologData);
    }, function(err) {
      // Add error handling for getPrologFarm2—critical for debugging!
      console.error('Error fetching from getPrologFarm2:', err);
      return res.status(500).json({ error: 'Failed to load Prolog farm data' });
    });
  }, function(err) {
    // Don't forget error handling for getFarmacias too
    console.error('Error fetching farmacias:', err);
    return res.status(500).json({ error: 'Failed to load farmacias data' });
  });
});

Key Fixes & Improvements:

  • Async flow control: We only call getPrologFarm2 after getFarmacias has returned data, so we avoid race conditions and ensure we don’t cut off the Prolog request early.
  • No more synchronous sleep: We removed sleep(2000)—async code should always use callbacks (or Promises) instead of blocking the event loop.
  • Proper error handling: Added error callbacks for both API calls. This will help you debug if the Prolog service itself is failing (e.g., timeout, internal error) instead of just seeing a vague "socket hang up" message.
  • Clarified loop index: Fixed the loop to start at 0 (adjust back to 1 if you intentionally skip the first item, but add a comment to explain why).

If the Error Still Happens:

  • Test the getPrologFarm2 endpoint directly with curl or Postman to make sure it’s reachable and returns data correctly.
  • Check if getPrologFarm2 takes longer to respond than getFarmacias—you might need to increase the timeout in your HTTP client (check the docs for whatever client library you’re using).
  • Verify there are no network issues (firewalls, proxies) between your Node.js server and the Prolog service.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 07:47:10