【问题标题】:Get Reqeust fails with Error: connect ECONNREFUSED获取请求失败并出现错误:连接 ECONNREFUSED
【发布时间】:2019-06-12 15:33:26
【问题描述】:

我正在尝试向服务器发送一个获取请求。但是我收到以下错误,知道如何避免错误吗?

错误:

events.js:183 投掷者; // 未处理的“错误”事件 ^

错误:连接 ECONNREFUSED ****** 在 Object._errnoException (util.js:992:11) 在 _exceptionWithHostPort (util.js:1014:20) 在 TCPConnectWrap.afterConnect [as oncomplete] (net.js:1186:14)

我的要求:

var https = require("https");

// Update these options with the details of the web service you would like to call
var options = {
  method: 'GET',
  uri: 'https:*****',
  resolveWithFullResponse: true,
  json: true
};

var req = https.request(options, res => {
  res.setEncoding('utf8');
  var returnData = "";

  res.on('data', chunk => {
    returnData = returnData + chunk;
  });
  res.on('end', () => {
    console.log('returndata: ' + JSON.stringify(returnData))
    var pop = JSON.parse(returnData).population;
    callback(pop);
  });
});
req.end();

【问题讨论】:

    标签: javascript node.js get-request


    【解决方案1】:

    这是一个例子,你不能像这样在选项对象上设置 uri,你要么使用 uri 字符串/URI 对象,要么为此请求类型使用选项对象(请参阅Node.js http.request docs

    const https = require('https');
    
    const options = {
        hostname: 'jsonplaceholder.typicode.com',
        path: '/todos/1',
    };
    
    const req = https.request(options, (res) => {
        let returnData = "";
    
        res.on('data', chunk => {
            returnData = returnData + chunk;
        });
    
        res.on('end', () => {
            console.log('returndata: ', returnData);
        });
    });
    
    req.on('error', (e) => {
        console.error(e);
    });
    
    req.end();
    

    【讨论】:

      【解决方案2】:

      有两种方法可以定义要传递给https.request()的请求选项:

      1. 通过将hostnamepath 和(可选)port 指定为单独的请求选项:

        var options = {
          method: 'GET',
          hostname: 'jsonplaceholder.typicode.com',
          path: '/posts/1',
          port: 443
        };
        
      2. 通过使用创建url.URL 的实例:

        var URL = require('url').URL;
        var options = new URL('https://jsonplaceholder.typicode.com/posts/1');
        

        更多信息请参考官方documentation

      【讨论】:

        猜你喜欢
        • 2016-03-02
        • 1970-01-01
        • 2011-07-13
        • 1970-01-01
        • 1970-01-01
        • 2021-12-05
        • 1970-01-01
        • 2020-06-18
        • 2020-12-28
        相关资源
        最近更新 更多