Nodejs - https.request错误:连接ECONNREFUSED

时间:2017-06-06 07:53:18

标签: node.js econnrefused

我正在尝试在我的节点服务器中进行http调用(我正在尝试的URL是skackexchange公共URL),下面是代码

httpsServer.js

var https = require('https');

function httpsRequest() {
    var options = {
        hostname: 'api.stackexchange.com',
        path: '/2.2/answers',
        method: 'GET'
    };

    var req = https.request(options, (res) => {
        res.on('data', function (data) {
            console.dir(data);
        });
        req.end();
    });

    req.on('error', function (e) {
        console.error(e);
    });
}

httpsRequest();

而且我在我的控制台中node httpsServer

但我收到以下错误。

Error:

{ Error: connect ECONNREFUSED xxx.xxx.xxx.xx:443
    at Object.exports._errnoException (util.js:1050:11)
    at exports._exceptionWithHostPort (util.js:1073:20)
    at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1093:14)
  code: 'ECONNREFUSED',
  errno: 'ECONNREFUSED',
  syscall: 'connect',
  address: 'xxx.xxx.xxx.xx',
  port: 443 }

注意:我在代理服务器后面。

我做错了什么?如果它因为我落后于代理是否有办法让它起作用?

1 个答案:

答案 0 :(得分:0)

您的req.end()位置错误。您需要先结束您的请求,然后才能从服务器获得响应。

var https = require('https');
function httpsRequest() {
    var options = {
        hostname : 'api.stackexchange.com',
        path : '/2.2/answers',
        method : 'GET'
    };
    var req = https.request(options, (res) => {
        res.on('data', function (data) {
            console.dir(data);
        });
    });
    req.on('error', function (e) {
        console.error(e);
    });
    req.end(); // correct place
}
httpsRequest();