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

使用原生JavaScript调用Strapi API渲染HTML时显示undefined的解决方法

问题

使用原生JavaScript向自建Strapi API发起fetch请求,请求可正常触发,但页面渲染结果为undefined。已确认需使用data.data.forEach而非data.forEach遍历数据,但无法正确获取author字段。相关代码及API返回结构如下:

Fetch 请求代码

function getSprites() {
    const div = document.getElementById('hello')
    fetch('http://localhost:1337/api/sprites')
    .then(res => res.json())
    .then(data => {
      data.data.forEach(sprite => {
        div.innerHTML += `
        <li>${sprite.author}</li>
        `
      })
    })
  }

getSprites();

HTML 代码

<div id="hello" class="sprite-container"></div>

API 返回的 JSON 结构

{
  "data": [
    {
      "id": 1,
      "attributes": {
        "title": "Example",
        "author": "Rosabelle",
        "submitter": "Exmaple",
        "createdAt": "2023-11-27T13:08:56.236Z",
        "updatedAt": "2023-11-27T14:08:29.447Z",
        "publishedAt": "2023-11-27T13:09:10.204Z"
      }
    }
  ],
  "meta": {
    "pagination": { "page": 1, "pageSize": 25, "pageCount": 1, "total": 2 }
  }
}

解决方案

问题出在字段的嵌套路径上:Strapi API返回的每个sprite数据中,author等自定义字段都嵌套在attributes对象里,直接访问sprite.author自然会得到undefined。

只需将sprite.author改为sprite.attributes.author即可正确获取作者信息。

修改后的 Fetch 请求代码

function getSprites() {
    const div = document.getElementById('hello')
    fetch('http://localhost:1337/api/sprites')
    .then(res => res.json())
    .then(data => {
      data.data.forEach(sprite => {
        div.innerHTML += `
        <li>${sprite.attributes.author}</li>
        `
      })
    })
  }

getSprites();

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 05:03:14