Error: getaddrinfo ENOTFOUND while making get request to localhost, Nodejs

Error: getaddrinfo ENOTFOUND while making get request to localhost, Nodejs

我正在尝试通过节点 http 模块向我本地的 etcd 实例 运行 发出 het 请求。

代码如下所示

'use strict';
const express = require('express');
const app = express();
var http = require('http');

const port = 10111;

var encoded_url = encodeURI('/v2/keys/message -X GET');

var options = {
  host: 'http://127.0.0.1:2379',
  path: encoded_url
};

var callback = function (response) {
  var str = '';

  //another chunk of data has been recieved, so append it to `str`
  response.on('data', function (chunk) {
    str += chunk;
  });

  //the whole response has been recieved, so we just print it out here
  response.on('end', function () {
    console.log(str);
  });
}

http.request(options, callback).end();

app.listen(port, () => {
  console.log("server started on port " + port);
});

但我收到以下错误

Error: getaddrinfo ENOTFOUND http://127.0.0.1:2379 http://127.0.0.1:2379:80
    at errnoException (dns.js:28:10)
    at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:76:26)

如果我从终端发出相同的 curl 请求,我会得到结果

curl http://127.0.0.1:2379/v2/keys/message -X GET

无法弄清楚是什么问题。

默认http.request()使用端口80

改用这个:

var options = {
  protocol: 'http:',
  host: '127.0.0.1',
  port: 2379,
  path: encoded_url
};