1
votes

I'm trying to send a get request to the server. But I'm getting the following error, any idea how to avoid the error?

the error:

events.js:183 throw er; // Unhandled 'error' event ^

Error: connect ECONNREFUSED ****** at Object._errnoException (util.js:992:11) at _exceptionWithHostPort (util.js:1014:20) at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1186:14)

my request:

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();
2

2 Answers

0
votes

Here's an example, you can't set uri on the options object as such, you either use a uri string / URI object or you use the options object for this request type (see 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();
0
votes

There are two ways to define request options to be passed to https.request():

  1. By specifying hostname, path and (optionally) port as separate request options:

    var options = {
      method: 'GET',
      hostname: 'jsonplaceholder.typicode.com',
      path: '/posts/1',
      port: 443
    };
    
  2. By using creating an instance of url.URL:

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

    For more information please refer to the official documentation.