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

调用Fetch API时出现TypeError: Cannot read properties of undefined (reading 'forEach')错误求助

问题分析与解决

错误根源

  1. API返回结构不符预期:你调用的接口返回的是单个全局统计对象,不存在records数组字段,所以d.records为undefined,无法执行forEach方法。
  2. 变量名不匹配:循环参数定义为values,但模板字符串里误用了未定义的v,会引发后续渲染错误。

修正代码

JavaScript 代码

fetch("https://js.cexplorer.io/api-static/basic/global.json")
  .then(res => res.json())
  .then(d => {
    let data1 = "";
    // 直接使用返回的单个对象,无需循环遍历
    data1 += `<div class="card">
        <p class="name">创世供应量: ${d.data.supply.genesis}</p>
        <p class="occupation">最大供应量: ${d.data.supply.max}</p>
      </div>`;

    document.querySelector(".test").innerHTML = data1;
  })
  .catch(e => console.log(e));

HTML 代码

<div class='test'></div>

额外优化建议

  • 调试时可先在.then(d => {})中添加console.log(d),直观查看返回的数据结构,避免格式误判。
  • 增加请求成功校验,提升代码健壮性:
fetch("https://js.cexplorer.io/api-static/basic/global.json")
  .then(res => {
    if (!res.ok) throw new Error("请求失败");
    return res.json();
  })
  .then(d => {
    // 后续渲染逻辑
  })
  .catch(e => console.log(e));

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 18:31:50