PokeAPI Javascript 仅检索名称和 URL

亚历山大·阿里亚斯-阿吉拉尔

我想访问 json 文件中的 Pokémon 类型。

但是,看起来我只能检索名称和 url,知道我做错了什么吗?

const baseUrl = 'https://pokeapi.co/api/v2/pokemon/?limit=3000'
try {
    fetch(baseUrl)
        .then(response => {
            const responseJson = response.json()
            return responseJson
        })
        .then(data => {
            const pokemons = data.results
            pokemons.forEach(pokemon => {
                console.log(pokemon);
            })
        })
        .catch(error => {
            console.error(error)
        })
} catch (error) {
    console.error(error)
}

在此处输入图像描述

雷诺C5

实际上,这就是 API 的完成方式。

如果您想获得更多关于口袋妖怪的值,您需要从第一个结果中通过给定 URL 发出另一个请求。

这可以使用内部的另一个 axios 调用来完成then

const baseUrl = 'https://pokeapi.co/api/v2/pokemon/?limit=1'
try {
    fetch(baseUrl)
        .then(response => {
            const responseJson = response.json()
            return responseJson
        })
        .then(async data => {
            const pokemons = data.results
            for (const pokemon of pokemons){
              pokemon.data = await fetch(pokemon.url).then(res => res.json())
            }
            
            console.log(pokemons)
        })
        .catch(error => {
            console.error(error)
        })
} catch (error) {
    console.error(error)
}

请注意,API 非常慢,这就是为什么我建议使用分页而不是limit=3000您所做的广告。

这可以使用offset作为分页开始的参数来完成

例如,?offset=20&limit=20将获得 20 和 40 之间的 20 个口袋妖怪

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章