You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

调用GitHub用户API后data.forEach is not a function报错如何解决?

报错原因

你调用的GitHub单用户查询接口 https://api.github.com/users/{用户名} 返回的是单个用户信息对象,而forEach是仅数组可用的遍历方法,对对象调用自然会触发该类型错误。

修复方案

直接修改displayResult函数,去掉不必要的遍历逻辑,同时补充异常处理、修正原代码中bio字段取值错误的问题,修正后的完整JS代码如下:

const searchUser = () => {
    const searchField = document.getElementById('seacrh-field');
    const searchText = searchField.value.trim();
    if(!searchText) return alert('请输入要查询的GitHub用户名');
    console.log(searchText);
    searchField.value = '';
    const url = `https://api.github.com/users/${searchText}`
    fetch(url)
        .then(res => {
            if(!res.ok) throw new Error('用户不存在或请求失败')
            return res.json()
        })
        .then(data => displayResult(data))
        .catch(err => alert(err.message));

}

const displayResult = profile => {
    const showResult = document.getElementById('displayResult');
    showResult.innerHTML = '';
    const div = document.createElement('div');
    div.classList.add('display-result');
    div.innerHTML = `
            <div class="img">
                <img src="${profile.avatar_url}" alt="avatar">
            </div>
            <div class="details">
                <div class="info">
                <h3>Name: ${profile.name || '未设置'}</h3>
                <p>username:${profile.login}</p>
                <p>bio:${profile.bio || '未设置'}</p>
                <p>Created:${new Date(profile.created_at).toLocaleDateString()}</p>
                <p>total-repo:${profile.public_repos}</p>
                <p>followers:${profile.followers}</p>
                <p>following: ${profile.following}</p>
                 
            </div>
            </div>
    `;
    showResult.appendChild(div);
}

修改点说明

  • 移除了data.forEach遍历逻辑,直接使用返回的单个用户对象渲染页面
  • 补充了空输入校验、接口请求异常捕获逻辑,避免请求失败时无反馈
  • 修正了原代码中bio字段错误取profile.name的问题
  • 补充了空值兜底展示、创建时间格式化的优化,避免字段为空时显示undefined

内容的提问来源于stack exchange,提问作者Hasibul Polok

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 18:54:04