調用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如何解決它(而不是人爲地延遲它)。
也許響應已經JSON格式,也沒有必要來分析呢?嘗試刪除'JSON.parse'的數據 – Edgar
@Edgar我得到一個原始緩衝區,甚至偶爾成功格式化爲JSON。 –