函数没有正确返回JSON

时间:2017-06-13 10:12:20

标签: json node.js

我已经编写了一个小代码片段来从第三方服务中获取引用 -

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' }

虽然接收到正确的输出,但它不会在函数中返回。 我该如何解决这个问题?

1 个答案:

答案 0 :(得分: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);