首页 > 解决方案 > 我一直在尝试获取 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 输入意外结束

标签: javascriptapi

解决方案


您的 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>


推荐阅读