无法找到解决方案:JSON.parse:第1行第1列的数据意外结束

时间:2019-06-03 17:15:11

标签: javascript api http

我正在尝试构建一个基本的React应用程序,该应用程序可以访问API以获取引号。 “ GET”请求返回一个字符串,但是,当我尝试将字符串解析为JSON时,就是收到错误。

这是我发出请求的功能:

const httpCallout = () => {
  const Http = new XMLHttpRequest();

  const endpoint = "http://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1";
  Http.open("GET", endpoint, true);
  Http.send();
  let reply = "";

  Http.onreadystatechange = (e) =>{
      console.log(JSON.parse(Http.response));
      //console.log(Http.response);
  }
  return reply;
}

以及来自服务器的解析响应:

[
  {
    "ID": 1286,
    "title": "Adrian Shaughnessy",
    "content": "<p>Graphic design has been likened to a wine glass. When we drink wine we barely notice the glass it&#8217;s served in. It wouldn&#8217;t be true to say that we don&#8217;t care what glass we drink out of &#8211; we wouldn&#8217;t choose to drink a rare vintage out of a Tupperware mug, for example &#8211; but it&#8217;s the wine that matters, not the vessel it comes in.   </p>\n",
    "link": "https://quotesondesign.com/adrian-shaughnessy/",
    "custom_meta": {
      "Source": "<a href=\"http://observatory.designobserver.com/entry.html?entry=7257\">transcript</a>"
    }
  }
]

我也在寻找非jQuery响应。同样,控制台抛出的全部错误是:SyntaxError: JSON.parse: unexpected end of data at line 1 column 1 of the JSON data,并在第console.log(JSON.parse(Http.response));行给出错误

2 个答案:

答案 0 :(得分:1)

您的方法中有几处错误。

1.-发出“ http”请求是不安全的,因为浏览器会将其标记为不安全,而是使用https。

2.-您收到的答案无效,无法创建JSON.parse。

我推荐这段更简洁的代码:)

Private Sub PA_Change()
    Me.object.Visible = PA.Value ' TODO: give 'object' an actual name
End Sub

答案 1 :(得分:0)

阅读onreadystatechange的文档:

https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/onreadystatechange

仅当readyState设置为4时,该响应才可用,但多次执行回调(在响应到达之前)。

要解决此问题,请确保仅在response实际使用时对其进行处理。

或者,您可能更喜欢使用不直观的新API在浏览器中执行HTTP请求:fetch()

https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API