javascript - 我一直在尝试获取 API,但我不断收到:SyntaxError: Unexpected end of JSON
问题描述
我曾多次尝试使用 fetch 获取 API,但我得到的承诺让我头疼。这是我得到的错误,JSON输入意外结束
我在网上查过,包括堆栈溢出,但他们在前面的问题中给出的解决方案并没有解决我的问题。这对我来说看起来很不寻常
search(){
let{ingredients, dish} = this.state;
const url = `http://www.recipepuppy.com/api/?i=${ingredients}&q=${dish}`;
fetch(url, {
method: 'GET'
})
.then(response => response.json())
.then(json => console.log('recipe', json))
.catch(err => console.log(err));
}
未捕获(承诺中)SyntaxError:JSON 输入意外结束
解决方案
您的 json 响应(您在有问题的评论中提供)无效
let json='{"title":"Recipe Puppy","version":0.1,"href":"http:\/\/www.recipepuppy.com\/","results":[{"title":"Simple Tuna Pasta Salad","href":"http:\/\/www.recipezaar.com\/Simple-Tuna-Pasta-Salad-64320","ingredients":"albacore tuna, celery, peas, mayonnaise, pasta (in general), salt","thumbnail":"http:\/\/img.recipepuppy.com\/38156.jpg"}'
JSON.parse(json); // Uncaught SyntaxError: Unexpected end of JSON input
]}
您的服务器需要在返回的 json 末尾加入额外的
日期
您需要在服务器中打开 cors - 如果您无权访问服务器,则需要使用一些 cors-proxy,例如下面(但不要将其用于生产)
async function load(ingredients,dish) {
let url=`http://www.recipepuppy.com/api/?i=${ingredients}&q=${dish}`;
let nocors= `https://cors-anywhere.herokuapp.com/`
let data = await (await fetch(nocors+url)).json();
console.log(data);
}
<button onclick="load('fish','taco')">Load</button>
推荐阅读
- vue.js - Vue.js 绑定模型将字符串转换为数字
- java - 将 java 类转换为 jar 并将其用作外部库
- javascript - 使用 Javascript 和 html 拖放
- javascript - 当我们在 FLEX LAYOUT 的 fxFlex 中使用时,角度材料日期选择器宽度太长
- vb.net - 如何在 VB.Net 数据网格中禁用单元格编辑?
- prestashop - 提取产品的所有类别 ID
- angular - 使用 Firebase 使用本地化部署 Angular 10 应用
- html - 使元素高度整页
- css - 是否可以使用 CSS 定义可在类中使用的指定颜色值列表?
- c# - 使用 ASP.NET Core 和 SQL Server 在传单地图上动态添加标记