首页 > 解决方案 > 获取“未处理的拒绝(SyntaxError):JSON 输入的意外结束”

问题描述

这是我的代码:

const userIds: string[] = [
    // Squall
    '226618912320520192',

    // Tofu
    '249855890381996032',

    // Alex
    '343201768668266496',

    // Jeremy
    '754681236236140666',

    // Maddo
    '711211838305599538',

    // Arden
    '375573674306306050',

    // Neo
    '718874307316678698',

    // Mytho
    '480092510505402380',

    // Yuun
    '630427600220717067'
];
const fetchData = async() => {
    let users: User[] = [];
    for (const id in userIds) {
        const response = await fetch('https://api.codetabs.com/v1/proxy/?quest=http://hamsterland.herokuapp.com/api/users?id=' + id);
        const user: User = await response.json(); 
        users.push(user);
    }
}

我得到错误Unhandled Rejection (SyntaxError): Unexpected end of JSON input

如果我分别使用每个 Id 的 API,都返回有效的 JSON。for但是,它在循环中不起作用。

标签: javascriptreactjstypescriptfetch

解决方案


如果你只是这样做

for (const id in userIds) {
    console.log(id);
}

你会看到问题。在这个循环中,id,而不是。您可能会得到404s 作为回报。

使用for... of循环而不是for... in.


推荐阅读