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

使用Axios+Node.js调用PokeAPI获取宝可梦Stats时返回undefined求助

问题:Pokemon API获取HP、攻击、速度属性返回undefined

我在使用Pokemon API时遇到了问题,获取攻击、HP和速度属性(stats)时,所有宝可梦的这些字段都显示undefined!

我的API调用代码

const axios = require('axios');

const apiPokemon = async () => { 
    try {
        const pokemons = await axios
        .get('https://pokeapi.co/api/v2/pokemon?limit=50')
        const secondUrlMap = await  pokemons.data.results.map(  pokemon  => {
            return pokemon.url
        })
        const pokemonArr = await Promise.all(secondUrlMap.map(async(url) => { 
            const urlResponse = await axios(url)
            return{
                id:urlResponse.data.id,
                name:urlResponse.data.name,
                height:urlResponse.data.height,
                weight:urlResponse.data.weight,
                hp:urlResponse.data.stats.find(stat => stat.name === 'hp')?.base_stat,
                attack:urlResponse.data.stats.find(stat => stat.name === 'attack')?.base_stat, 
                speed:urlResponse.data.stats.find(stat => stat.name === 'speed')?.base_stat,
                types:urlResponse.data.types.map((type) => type.type.name),
                img:urlResponse.data.sprites.other['official-artwork'].front_default,
            }
        }))
        return pokemonArr
    } catch (error) {
        return ({error:error.message})
    }
}

module.exports =  {
    apiPokemon,
}

测试代码及结果

我用index.js测试API返回结果,代码如下:

const { apiPokemon } = require('./apiPokemon')

async function testApi() { 
    const pokemons = await apiPokemon()
    console.log(pokemons)
}

testApi()

控制台输出:
控制台输出

API结构

API结构


解决方案

问题出在stats数组的遍历逻辑上:Pokemon API返回的stats数组中,每个元素的属性名称并不在顶层,而是嵌套在stat对象里。

从API结构能看到,单个stats元素的结构是:

{
  "stat": {
    "name": "hp",
    "url": "..."
  },
  "base_stat": 45,
  ...
}

你需要把find方法的判断条件从stat.name改成stat.stat.name,修改后的代码片段如下:

hp:urlResponse.data.stats.find(stat => stat.stat.name === 'hp')?.base_stat,
attack:urlResponse.data.stats.find(stat => stat.stat.name === 'attack')?.base_stat, 
speed:urlResponse.data.stats.find(stat => stat.stat.name === 'speed')?.base_stat,

修改后就能正确匹配到对应的属性,获取到base_stat的有效值了。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 22:05:09