2013-03-24 57 views
0

我是node.js中的一個begginer,現在我試圖從http.get獲取API的結果。但是,當運行代碼時,我收到此錯誤:嘗試在node.js中使用http.get訪問API時出錯

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

我需要正確的HTTP(我不得不測試它,以確保) 這裏是我的功能來說明這個問題:

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); 
    }); 

} 

,把它這種方式:

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

希望你能幫助我,謝謝!

回答

1

您必須使用https而不是http模塊。請參見http://nodejs.org/api/https.html 在選項對象中,「主機」應該只是主機名,即api.twitter.com。 指定端口不是必需的,但https的情況下「80」是錯誤的。 HTTPS是443,除非另有明確規定。

可以產生這樣的正確的選項:

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

爲了提高效率,功能的parseURL最好地的功能的getData外部定義。

如果您的getData函數支持http和https url都很重要,那麼您可以檢查parsedURL.protocol。如果「https」,則使用https.get,如果「http」,則使用http.get

+0

總是嘗試使用'hostname'而不是'host',因此您可以使用'url.parse()'(按照[文檔](http://nodejs.org/api/http.html#) http_http_request_options_callback))。 – Chad 2013-03-24 01:20:56

+0

謝謝你們兩位!現在它正在運行! – fnnrodrigo 2013-03-24 01:24:48

+0

感謝您的評論乍得。我相應地編輯了我的答案。 – 2013-03-24 01:32:38

相關問題