【发布时间】:2016-03-08 13:55:15
【问题描述】:
我在 http 请求函数中调用异步函数。调用的异步函数执行另一个 http 请求,但该 http 请求抛出错误 Error: socket hang up
代码
var http = require("http");
var fs = require('fs');
var url_1 = "en.wikipedia.org";
var url_2 = "www.twitter.com";
var options = { host: url_1, port: 80, path: '', method: 'POST'};
var api_options = { host:url_2, port: 80,path: '',method: 'POST' };
function async(arg, callback) { //async function declaration
console.log("received argument "+ arg);
http.request(options, function(res){ //http request to url_2
console.log("also the second http request successful");//this log not getting printed, insted http.request function in the previous line throws Error : socket hang up
return callback(arg);
});
}
http.request(options, function(res) { //http request url_1
console.log("first http request successful");
async("1",function(return_value){ //calling asynchronous function
console.log("count : "+ return_value + " returns callback");
});
}).end();
在上面的代码中,首先我向url_1 发出http 请求,请求后我正在调用async 函数,该函数试图向url_2 发出http 请求,但url_2 内部的http 请求async 函数只是返回我上面提到的错误。
结果
first http request successful
received argument 1
events.js:141
throw er; // Unhandled 'error' event
^
Error: socket hang up
at createHangUpError (_http_client.js:203:15)
at Socket.socketOnEnd (_http_client.js:288:23)
at emitNone (events.js:72:20)
at Socket.emit (events.js:166:7)
at endReadableNT (_stream_readable.js:905:12)
at doNTCallback2 (node.js:441:9)
at process._tickCallback (node.js:355:17)
Process exited with code: 1
我是 node.js 的新手,所以如果这是一个愚蠢的问题,请原谅
【问题讨论】:
-
这确实引出了一个问题:
url_2在任何情况下都能正常工作吗? -
在某种意义上的任何条件下我都无法得到你? ,你能不能再详细点
-
很有可能
url_2正在关闭 TCP 连接,原因与您的代码无关。可以直接拨打url_2得到结果吗?这种错误看起来像是您的请求格式不正确,在某种程度上。 -
这个程序只是一个大程序的骨架,我必须在另一个http_requested函数中对url_2进行http请求,这个程序只是描述了大程序的控制流程。但是感谢您提出可能是什么错误的建议,我将尝试修改代码
标签: javascript node.js sockets http asynchronous