使用fetch获取IP归属地时if/else判断输出错误如何解决
问题原因
你直接将接口返回的完整JSON对象和字符串JP做等值判断,判断逻辑永远不成立,所以始终走else分支。ipinfo.io返回的IP归属国家码存放在响应对象的country属性中,需要取该属性值再做判断。
修改后的完整代码
async function country() { let response = await fetch("https://ipinfo.io/json?token=8a21f471f4e583") let CountryResponse = await response.json() console.log(CountryResponse) if (CountryResponse.country === "JP") { console.log('You are in Japan'); } else { console.log('I guess you are in the USA'); } } country()
内容的提问来源于stack exchange,提问作者Arnes Kuduzovic
相关产品推荐
相关产品推荐

