2017-02-19 99 views
0

調用Riot-Api Im在https GET請求中接收不完整的JSON。Node.js https-module不完整的JSON響應

調試後,我意識到,取決於我等待多少(斷點)預先執行https'on'data'回調Im實際上接收完整的JSON對象。

(API平均響應時間對我來說是200-300ms)

let getOptions = function(url) { 
    return { 
    host: 'na.api.pvp.net', 
    port: 443, 
    path: `${url}?api_key=${apiKey}`, 
    method: 'GET' 
    }; 
} 

exports.Call = function(url, callback) { 
    let response = {}; 

    let req = https.request(getOptions(url), function(res) { 
    response.statusCode = res.statusCode; 
    res.on('data', function(data) { 
     response.json = JSON.parse(data); 
     callback(response); 
    }); 
    }); 

    req.on('error', function(err) { 
    response.err = err; 
    callback(response); 
    }); 

    req.end(); 
}; 

運行的代碼,而斷點或只打破了很短的時間我要麼運行到錯誤:

JSON.parse(data): Unexpected Token in JSON at position ... 

JSON.parse(data): Unexptected end of JSON Input. 

正如我所期待的'數據'回調只有在請求完成後才能執行im confused abo如何解決它(而不是人爲地延遲它)。

+0

也許響應已經JSON格式,也沒有必要來分析呢?嘗試刪除'JSON.parse'的數據 – Edgar

+0

@Edgar我得到一個原始緩衝區,甚至偶爾成功格式化爲JSON。 –

回答

0

http.request返回stream - 它不是一個包含整個響應的簡單回調。 如果你想解析整個迴應,你將不得不去buffer and concatenate

我強烈電子書籍使用一個輔助庫像gotrequest

+0

無法看到樹木的森林..非常感謝 - 使用請求截至目前:) –