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

使用点符号访问Axios返回的JSON数据时获取到undefined的问题

解决Epic Games免费游戏API数据访问返回undefined的问题

问题原因

你出错的核心原因是elements是数组类型,不是单个对象。直接用点符号访问elements.promotions相当于在数组上查找promotions属性,自然返回undefined。从API响应结构来看,searchStore.elements里是多个游戏条目,每个条目才包含promotions字段。

解决步骤

  1. 确认数据结构层级
    先打印完整的response.data.data.Catalog.searchStore,明确elements的数组类型:

    axios.get('https://store-site-backend-static.ak.epicgames.com/freeGamesPromotions?locale=en-US&country=US&allowCountries=US')
      .then(response => {
        console.log(response.data.data.Catalog.searchStore.elements); // 此处会输出游戏条目数组
      })
      .catch(err => console.error(err));
    
  2. 遍历数组获取每个条目的promotions
    因为elements是数组,需要遍历它来逐个访问游戏的promotions:

    axios.get('https://store-site-backend-static.ak.epicgames.com/freeGamesPromotions?locale=en-US&country=US&allowCountries=US')
      .then(response => {
        const gameList = response.data.data.Catalog.searchStore.elements;
        // 遍历所有游戏条目
        gameList.forEach(game => {
          if (game.promotions) {
            console.log(game.promotions);
          } else {
            console.log('该游戏无促销信息');
          }
        });
      })
      .catch(err => console.error(err));
    
  3. 可选:获取单个游戏的促销信息
    若只需第一个游戏的促销数据,可通过数组索引直接访问,建议搭配可选链避免报错:

    const firstGamePromotions = response.data.data.Catalog.searchStore.elements[0]?.promotions;
    console.log(firstGamePromotions);
    

额外提示

  • 访问深层嵌套属性时,推荐使用可选链?.,避免因某一层级不存在导致的报错,示例:
    const promotions = response.data?.data?.Catalog?.searchStore?.elements?.[0]?.promotions;
    
  • 遇到嵌套数据问题时,先在控制台打印完整响应结构,确认每个层级的类型(对象/数组),再选择对应的访问方式(点符号/索引)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 16:20:42