套接字错误"代码":" ECONNREFUSED"尝试使用nodejs访问远程服务器时

时间:2017-10-07 19:55:40

标签: javascript node.js sockets tcp connection

我正在尝试连接到远程服务器,但每次我尝试创建连接时都会得到 套接字错误"代码":" ECONNREFUSED" ," errno":" ECONNREFUSED","系统调用":"连接","地址":" 127.0.0.1""端口":" 80"} 我的代码如下:

//create the connection
const client = net.createConnection({
    host: urlObj.host,
    port: urlObj.port
});


//on receiving the data, print it
client.on('data', function (data) {
    if (verbose) {
        console.log(data.toString());
    } else {
        //get rid of the head of the response if not verbose mode
        var responseSplit = data.toString().split("\r\n");
        var inBody = false;
        for (var i in responseSplit) {
            if (responseSplit[i] == "") {
                inBody = true;
            }
            if (inBody) {
                console.log(responseSplit[i]);
            }
        }
    }
});

//send the request
client.on('connect', () => {
    client.write(clientWritingString);
});

client.on('error', err => {
    console.log('socket error %j', err);
    process.exit(0);
});

我正在解析网址:

//parse the URL

var urlToParse = process.argv[process.argv.length - 1];
var urlObj = url.parse(urlToParse);
if(urlObj.port==null){
    urlObj.port=80;
} else {
    urlObj.host = urlObj.host.split(":")[0];
}

1 个答案:

答案 0 :(得分:0)

错误消息显示您的程序正在尝试访问您自己的计算机(= 127.0.0.1)。检查您正在为您的例程提供的原始URL,并确保解析器最终得到实际的远程URL。