使用fetch()请求接口可打印完整对象但访问属性返回undefined怎么办
问题原因
你调用的https://restcountries.com/v3/alpha/接口返回值为数组结构,而非你以为的国家信息对象。你打印完整json时看到的包含borders属性的对象,实际是数组的第一个元素。数组本身不存在borders属性,所以直接访问json.borders会得到undefined。
解决方法
取返回数组的第一个元素,再访问对应属性即可,修改后代码如下:
const response = await fetch(`https://restcountries.com/v3/alpha/${countrycode}`); let json = await response.json(); console.log("this is my json file: ", json[0].borders)
如果需要兼容异常场景避免报错,可以加层非空判断:
const response = await fetch(`https://restcountries.com/v3/alpha/${countrycode}`); let json = await response.json(); if (json?.length) { const countryInfo = json[0]; console.log("borders: ", countryInfo.borders); // 其他属性均从countryInfo读取即可,例如countryInfo.capital、countryInfo.name等 }
内容的提问来源于stack exchange,提问作者Kubaguette The Testobun
相关产品推荐
相关产品推荐

