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

如何借助async await渲染fetch请求获取的API接口数据

问题原因

  • 核心问题出在DOM选择器的使用上:document.querySelectorAll() 返回的是匹配选择器的所有元素组成的NodeList类数组集合,而非单个DOM元素,NodeList本身没有innerHTML属性,直接赋值不会生效。
  • 冗余代码:末尾单独调用的getIp()没有做返回值处理,属于无效代码,不影响功能但无实际作用。
  • 可选规范问题:变量名ipAdress为拼写失误,正确拼写为ipAddress,不影响运行但不符合命名规范。

修复方案

如果你确认页面中只有一个.ip容器下的p标签需要渲染IP,直接将querySelectorAll替换为querySelector即可,querySelector会直接返回第一个匹配选择器的单个DOM元素。

修正后的代码如下:

// GET PUBLIC IP
const getIp = async () => {
    const reqIp = await fetch("https://ipinfo.io/json?token=xxx")
    return reqIp.json()
}

document.addEventListener("DOMContentLoaded", async () => {
    const dataIp = await getIp()
    // 替换querySelectorAll为querySelector获取单个元素
    const ipAddress = document.querySelector('.ip p')
    ipAddress.innerHTML = dataIp.ip
})

如果你需要给多个匹配的p标签都赋值IP,可遍历NodeList逐个设置:

document.addEventListener("DOMContentLoaded", async () => {
    const dataIp = await getIp()
    const ipAddressList = document.querySelectorAll('.ip p')
    ipAddressList.forEach(el => {
        el.innerHTML = dataIp.ip
    })
})

内容的提问来源于stack exchange,提问作者TheDareback

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 23:54:04