调用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
相关产品推荐
相关产品推荐

