未捕获的参考错误:在Request.request

时间:2018-08-19 01:16:05

标签: json request

我正在尝试在我的电子应用程序中显示API调用的详细信息。 this is the api并采样json数据:

[
{
  ID: 596,
  title: "Carolyn Wood",
  content: "<p>Turning away bad clients can leave you feeling oddly guilty. They&#8217;re sort of like alcoholic or meth head cousins who force you, by their own bad behavior into denying them things you wouldn&#8217;t deny other people. You&#8217;re left feeling not quite yourself. </p> ",
  link: "https://quotesondesign.com/carolyn-wood/",
  custom_meta: {
    Source: "<a href="http://twitter.com/carywood/status/2121020860">Twitter</a>"
   } 
 }
]

我正在使用request模块来获取数据,并使用JSON.parse(body)来获取如下对象:

let request = require('request');
request("http://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1&_jsonp=mycallback",
(err, response, body)=>{
let jsonBody = JSON.parse(body);
let randQuote = jsonBody[0]["content"];
document.getElementById("quote").innerHTML = randQuote;
});

在控制台中,出现此错误:

Uncaught ReferenceError: jsonBody is not defined
at Request.request [as _callback] (D:\ElectronDev\ElectronBasics\quote-widget\index.js:8

指向此行JSON.parse(body)。我该如何解决?

1 个答案:

答案 0 :(得分:0)

来自端点的响应在响应的开头有一些额外的字符,这就是JSON.parse无法将其解析为对象并且jsonBody未定义的原因。

这是您对this的特定回复的解决方法。将您的代码行更改为此。

let jsonBody = JSON.parse(body.substring("/**/mycallback(".length, body.length - 1));

希望这会有所帮助。