2016-05-23 42 views
0
getJSON('https://api.twitch.tv/kraken/streams/Jonathan_x64', 
function(channel) { 

    if (channel["stream"] == null) { 
     //do something 

    } else { 
     ////do something else 

    } 
}); 

這是我當前的代碼,但是當我運行它,我得到以下錯誤新建JSON在得到的NodeJS一些錯誤

if (channel["stream"] == null) { 
      ^

TypeError: Cannot read property 'stream' of undefined 
    at E:\my ultemet bot\index.js:10:16 
    at Request._callback (E:\my ultemet bot\node_modules\get-JSON\lib\node.js:11:5) 
    at Request.self.callback (E:\my ultemet bot\node_modules\request\request.js:200:22) 
    at emitTwo (events.js:106:13) 
    at Request.emit (events.js:191:7) 
    at Request.<anonymous> (E:\my ultemet bot\node_modules\request\request.js:1067:10) 
    at emitOne (events.js:101:20) 
    at Request.emit (events.js:188:7) 
    at IncomingMessage.<anonymous> (E:\my ultemet bot\node_modules\request\request.js:988:12) 
    at emitNone (events.js:91:20) 
+0

您是否檢查過模塊文檔? https://github.com/zeke/get-json - 回調接收兩個參數:錯誤和響應。 – ahwayakchih

回答

2

據我所知,沒有一個內置的頂部級別爲getJSON()函數,因此您必須使用自定義函數。

從堆棧跟蹤你分享:

at Request._callback (E:\my ultemet bot\node_modules\get-JSON\lib\node.js:11:5) 
             ^^^^^^^^^^^^^^^^^^^^^ 

...我們瞭解到,您使用的是NPM third-party module。一旦出現,是微不足道的找到documentation

var getJSON = require('get-json') 

getJSON('http://api.listenparadise.org', function(error, response){ 

    error 
    // undefined 

    response.result 
    // ["Beth Orton &mdash; Stolen Car", 
    // "Jack White &mdash; Temporary Ground", 
    // "I Am Kloot &mdash; Loch", 
    // "Portishead &mdash; Glory Box"] 

    response.ok 
    // => true 

}) 

它不是真正的代碼,但很顯然,第一個回調參數爲error,但你有這樣的:

function(channel){} 

因爲(作爲錯誤消息狀態)它是undefined,這意味着呼叫成功 - 只是你沒有正確讀取它。


我一直在偷看模塊源代碼,它實際上不是很令人印象深刻。它基本上是request的一個小包裝,不會增加太多價值。

+0

那麼我該如何解決它? – SloppierKitty7

+0

只需定義回調函數,如文檔解釋。如果你不想要,你不需要使用第一個參數,但它必須在那裏! –