Node JS:通过'https'库调用外部HTTP请求

时间:2016-10-04 07:19:56

标签: javascript node.js https

当我通过基本的'https'库调用外部http请求时,我不能提到端口地址,但是当我显示日志错误时,它显示端口地址是'80'为什么它显示,我的代码中的问题在哪里? / p>

    var http = require("http");
    http.createServer(function (request, response) {
    var options = {
      hostname: 'example.com',
      method: 'GET',
      headers: {
                'Authorization':'Bearer 22bc5ce9f7934da6616ac7d883dbb8c9',
                'Content-Type': 'application/json'
      }
    };

    var req = http.request(options, (res) => {
      res.setEncoding('utf8');
      res.on('data', (chunk) => {
        console.log(`BODY: ${chunk}`);
      });
      res.on('end', () => {
        console.log('No more data in response.');
      });
    });
    req.end();
    req.on('error', (e) => {
      console.log(e);
    });


    // Listen on the 8080 port.
    }).listen(8080);

错误讯息:

{ Error: getaddrinfo ENOTFOUND https://example.com:80
    at errnoException (dns.js:28:10)
    at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:79:26)
  code: 'ENOTFOUND',
  errno: 'ENOTFOUND',
  syscall: 'getaddrinfo',
  hostname: 'https://example.com',
  host: 'https://example.com',
  port: 80 }

1 个答案:

答案 0 :(得分:0)

getaddrinfo ENOTFOUND表示客户端无法连接到指定的地址。请尝试指定不带http的主机。”试试这个:

var options = {
      host: 'example',
      method: 'GET',
      headers: {
                'Authorization':'Bearer 22bc5ce9f7934da6616ac7d883dbb8c9',
                'Content-Type': 'application/json'
      }
};

请参阅此帖子Here