0

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!

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Always try to use hostname instead of host, so you are compatible with url.parse() (as per the docs).
Thanks both of you! Now it is running!
Thanks for your comment Chad. I've edited my answer accordingly.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.