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

问题描述

我正在尝试构建一个基本的 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));

标签: javascriptapihttp

解决方案


您的方法有几处错误。

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

2.- 您收到的答案对于生成 JSON.parse 无效。

我会推荐这段更干净的代码:)

fetch('https://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1')
  .then(function(response) {
    return response.json();
  })
  .then(function(myJson) {
    console.log(myJson);
  });


推荐阅读