javascript - 无法找到解决方案: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’s served in. It wouldn’t be true to say that we don’t care what glass we drink out of – we wouldn’t choose to drink a rare vintage out of a Tupperware mug, for example – but it’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));
解决方案
您的方法有几处错误。
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);
});
推荐阅读
- java - JPA 规范对 CriteriaBuilder.or() 方法没有影响
- javascript - HighCharts - tickInterval 和 tickAmount 的问题
- c++ - 使用未初始化的局部变量,即使它在一开始就已初始化
- apache-spark - pyspark 中 col() 函数的使用
- html - 列表的最小高度以使用纯 CSS 至少适合 n 个列表项
- java - 单击按钮后如何将一个小程序表单调用到另一个表单
- java - 获取firebase数据的id
- mongodb - 如何在 mLab 中将集合从一个数据库复制到另一个数据库?
- xamarin.forms - System.Net.WebException:错误:TrustFailure(身份验证失败,请参阅内部异常。)
- java - 像 xsd 一样读取和创建 xml