为何循环无法将GitHub API返回的JSON数据渲染到页面?
解决"Cannot read property '0' of undefined"错误的GitHub仓库展示问题
嘿,我一眼就看出问题出在哪了!你在displayResults函数里的循环逻辑搞错了对象的访问方式:
你当前的代码里写了:
`<li> <a href="${response.url[i]}"> <p>${response.name[i]}</p> </li>`
但实际上,response是一个仓库对象的数组,每个仓库的具体信息都存在数组的每一项里(也就是response[i]才是单个仓库对象)。你应该访问response[i].url和response[i].name,而不是response.url[i]——因为response本身根本没有url或name属性,所以当你尝试读取response.url[0]的时候,response.url是undefined,自然就会抛出"Cannot read property '0' of undefined"的错误。
修正后的displayResults函数
function displayResults(response){ $('#results-list').empty(); // 先判断是否为有效数组,避免用户不存在时出错 if (!Array.isArray(response)) { $('#results-list').append('<li>该用户不存在或没有公开仓库</li>'); $('#results').removeClass('hidden'); return; } for(let i = 0; i < response.length; i++){ $('#results-list').append( `<li> <a href="${response[i].html_url}" target="_blank"> <p>${response[i].name}</p> </a> </li>` ) }; $('#results').removeClass('hidden'); };
顺便提个小细节:GitHub API返回的仓库数据里,url是API接口的地址,如果你想跳转到仓库的网页端,应该用html_url字段,我已经帮你替换成这个了,还加了target="_blank"让链接在新窗口打开,体验会更好。
额外优化:添加请求错误处理
现在你的代码没有处理请求失败的情况(比如网络错误、用户不存在返回404),可以在fetch链里加上.catch()来做友好提示:
function getUserRepos(){ var insertText = $('.inputBox').val(); fetch(`https://api.github.com/users/${insertText}/repos`) .then(response => { // 先判断HTTP状态是否成功 if (!response.ok) { throw new Error('用户不存在或请求失败'); } return response.json(); }) .then(response => { console.log(response) displayResults(response) }) .catch(error => { $('#results-list').empty(); $('#results-list').append(`<li>出错了:${error.message}</li>`); $('#results').removeClass('hidden'); }); };
这样不管是网络问题还是用户不存在,都能给用户清晰的提示,而不是只在控制台报错。
内容的提问来源于stack exchange,提问作者JacobAshley
相关产品推荐
相关产品推荐

