Node.js中Socket hang up错误:调用getPrologFarm2接口失败排查
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:
- The Prolog service’s
getPrologFarm2endpoint isn’t responding in time, or closes the connection unexpectedly. - Your Node.js code ends the HTTP response to your client before the
getPrologFarm2call 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
getPrologFarm2aftergetFarmaciashas 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
getPrologFarm2endpoint directly with curl or Postman to make sure it’s reachable and returns data correctly. - Check if
getPrologFarm2takes longer to respond thangetFarmacias—you might need to increase the timeout in your HTTP client (check the docs for whateverclientlibrary you’re using). - Verify there are no network issues (firewalls, proxies) between your Node.js server and the Prolog service.
内容的提问来源于stack exchange,提问作者Vasco Lusitano

