2017-06-13 118 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 –