2017-06-13 117 views
0

我已經寫了一小段代碼從第三方服務獲取報價 -功能沒有返回JSON正確

var http = require("https"); 

function getRandomQuote() 
{ 
var returnJson = {}; 
var options = { 
    "method": "GET", 
    "hostname": "talaikis.com", 
    "port": null, 
    "path": "/api/quotes/random/", 
}; 

http.get(options, function(resp){ 
    resp.on('data', function(chunk){ 
     console.log("Quote string - "+chunk.toString('utf8')); 
     returnJson = JSON.parse(chunk.toString('utf8')); 
     console.log(returnJson); 
     return returnJson; 
    }); 
    resp.on("error", function(e){ 
     console.log("Got error: " + e.message); 
    }); 
}); 

} 
var x = getRandomQuote(); 
console.log(x); 

輸出是 -

{} 
Quote string - {"quote":"Such an arrangement would provide Taiwan and China with a forum for dialogue whereby they may forge closer ties based on mutual understanding and respect, leading to permanent peace in the Taiwan Strait.","author":"Nick Lampson","cat":"respect"} 
{ quote: 'Such an arrangement would provide Taiwan and China with a forum for dialogue whereby they may forge closer ties based on mutual understanding and respect, leading to permanent peace in the Taiwan Strait.',author: 'Nick Lampson',cat: 'respect' } 

雖然正確的輸出接收它沒有在函數中返回。 我該如何解決這個問題?

回答

0

我認爲你的代碼的問題是你試圖解析每個塊,但基本上,你會收到無效的JSON對象。 嘗試修改你的代碼是這樣的:

const http = require("https"); 

function getRandomQuote() 
{ 
    let returnJson = {}; 
    const options = { 
    "method": "GET", 
    "hostname": "talaikis.com", 
    "port": null, 
    "path": "/api/quotes/random/", 
    }; 

    http.get(options, function(resp){ 
    let result = ""; 
    resp.on('data', function(chunk){ 
     result += chunk; 
    }); 
    resp.on('end', function(chunk) { 
     result += chunk; 
     returnJson = JSON.parse(result.toString('utf-8')); 
     console.log('Result:'); 
     console.log(returnJson); 
    }); 
    }).on("error", function(e){ 
    console.log("Got error: " + e.message); 
    }); 
} 


const x = getRandomQuote(); 
// this will fire 'undefined' 
console.log(x); 
+0

現在有一個新的錯誤 - 未定義 未定義:1個 語法錯誤:輸入 –

+0

意外結束我已經更新了,很可能這將解決這個問題 – Lazyexpert

+0

@Layexpert nope –