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

使用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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 15:09:00