fnnrodrigo
fnnrodrigo

Reputation: 83

Error when trying to acess API with http.get in node.js

I'm a begginer in node.js and now I'm trying to get API's result from http.get. But, when running the code I'm receiving this error:

Error: getaddrinfo ENOTFOUND
Error: getaddrinfo ENOTFOUND
at errnoException (dns.js:37:11)
at Object.onanswer [as oncomplete] (dns.js:124:16)

I'm requiring http correctly (I had it tested to be sure) Here is my function to illustrate the problem:

function getData(apiUrl, getUrl) {

    var options = {
        host : apiUrl,
        port : 80,
        path : getUrl
    };

    var content = "";

    http.get(options, function(res) {
        console.log("Got response: " + res.statusCode);

        res.on("data", function(chunk) {

            content += chunk;
            console.log(content);

        });

    }).on('error', function(e) {
        console.log("Error: " + e.message); 
        console.log( e.stack );
    });

}

And calling it this way:

getData('https://api.twitter.com', '/1/statuses/user_timeline.json?&screen_name=twitter&callback=?&count=1');

Hope you can help me, thanks!

Upvotes: 0

Views: 4485

Answers (1)

Myrne Stol
Myrne Stol

Reputation: 11438

You must use the https instead of http module. See http://nodejs.org/api/https.html In the options object, "host" should just be the hostname, i.e. api.twitter.com. Specifying port is not necessary, but "80" is wrong in case of https. HTTPS is 443, unless explicitly specified otherwise.

You can generate correct options like this:

    parseURL = require('url').parseURL;
    parsedURL = parseURL(apiURL);
    var options = {
        hostname : parsedURL.hostname,
        path : getUrl
    };

For efficiency, the parseURL function could best be defined outside of the getData function.

If it's important that your getData function supports both http and https urls, you could check parsedURL.protocol. If "https", then use https.get, if "http", then use http.get.

Upvotes: 1

Related Questions