0

I have a code like this:

  var options = {
            host: "https://basic:authentication@website.com",
            path: "/api/address"
  };


 var request = https.get(options, function(response){
            var str = "";
            response.on('data', function(chunk){
                    str+=chunk;
            });

            response.on('end', function(){
                    console.log(str);
                    res.json(str);
            });
    });

    request.end();

    request.on('error', function(err){
            console.log(err);
    });

This gives me

{ [Error: getaddrinfo ENOTFOUND] code: 'ENOTFOUND', errno: 'ENOTFOUND', syscall: 'getaddrinfo' }

I don't know what's wrong because if I change the request to look like this:

var request = https.get("https://basic:authentication@website.com/api/address", function(response){

It works and gets an answer from the api. The problem is that I can't input parameters into the call if I do it this way. Does anyone have tips?

Molehole
  • 65
  • 1
  • 6
  • If the server does not support parsing the body of `GET` requests, it would explain what you're seeing (cf. https://stackoverflow.com/questions/978061/http-get-with-request-body). If you need to specify parameters with a `GET`, is there a reason you cannot use query parameters instead? – miqh Nov 23 '15 at 23:33
  • There's over 30 query parameters. I would prefer not. It would be really messy. – Molehole Nov 23 '15 at 23:49
  • Understood - though I don't believe this is a problem with how you are using `https.get()` with Node. You could try issuing `GET` requests with bodies using an external client to confirm whether or not it is the server ignoring them. – miqh Nov 24 '15 at 00:07

1 Answers1

0

The problem is that your host value is not correct, it should really just be the hostname. For the HTTP basic auth, you can use the auth setting. For example:

var options = {
  host: "website.com",
  path: "/api/address",
  auth: "basic:authentication"
};

Also, explicitly calling request.end() is unnecessary since https.get() internally does that for you automatically.

I should also note that since it seems like you're responding to an existing request with a new, external request, you can simplify it further by simply piping the external response to the existing response:

https.get(options, function(response) {
  // You should probably check `response.statusCode` first ...
  res.set('Content-Type', 'application/json');
  response.pipe(res);
}).on('error', function(err) {
  // ...
});
mscdex
  • 104,356
  • 15
  • 192
  • 153