【问题标题】:APIs using fetch - cannot read property 'forEach' of undefined使用 fetch 的 API - 无法读取未定义的属性“forEach”
【发布时间】:2020-09-17 23:09:50
【问题描述】:

我正在尝试使用 API https://api.got.show/api/general/characters/ 从《权力的游戏》(节目)中提取所有角色的名称。我尝试了多种方法,但都失败了。现在它说“TypeError:无法读取未定义的属性'forEach'”,当我尝试使用其他API并且它可以工作时。我不知道该怎么办。到目前为止,这是我的代码:

<body>
    <h1>Game of thrones</h1>
    <select>
        <option id="characters"></option>
</select>
    <script>
        fetch('https://api.got.show/api/general/characters/')
            .then(data => data.json())
            .then(data_json => {
                console.log(data_json)
                show(data_json)
            })
            .catch(err => alert(`Ha habido un error. ${err}`))

        let show = data_json => {
            data_json.results.forEach((element, index) => {
                document.getElementById('characters').innerHTML += `<option class""character">${element.name}</option>`;
            });
        }
    </script>
</body>

【问题讨论】:

    标签: json api foreach fetch-api


    【解决方案1】:

    我尝试自己调用 API。看起来data_json 有两个属性bookshow,但没有results

    试试这个 sn-p 代替 show 函数:

    let show = data_json => {
      data_json.show.forEach((element, index) => {
        document.getElementById('characters').innerHTML += `<option class="character">${element.name}</option>`;
      });
    }
    
    

    【讨论】:

    • 非常感谢!现在它肯定显示了结果,剩下的必须工作!
    • 祝你好运!
    猜你喜欢
    • 1970-01-01
    • 2018-12-15
    • 1970-01-01
    • 1970-01-01
    • 2019-09-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-05
    相关资源
    最近更新 更多