axios 我试图获得和打印随机口袋妖怪使用API,但它给了我错误404

3zwtqj6y  于 2023-02-12  发布在  iOS
关注(0)|答案(1)|浏览(127)

这是API站点链接:https://pokeapi.co/docs/v2#pokemon
这是API示例:https://pokeapi.co/api/v2/pokemon/{id或名称}/
这是store.js

import { defineStore } from 'pinia'
import axios from 'axios'

let serverHost = 'https://pokeapi.co/api/v2'

export const pokeStore = defineStore("pokemons", {
  state: () => {
    return {
      pokemons: []
    };
  },
  actions: {
    async getOnePokemon(id) {
      try {
        let response = await axios.get(`${serverHost}/pokemon/${id}`)
        if(response.data){
          response.data.name = response.data.name.replace('-', " ");
        let pokemon = {
          id: response.data.id,
          name: response.data.name,
          image: response.data.sprites.front_default
        }
        if(!pokemon.image){
          pokemon.image = response.data.sprites.front_shiny
        }
        return pokemon
      }
      } catch (error) {
        this.getOnePokemon(Math.floor(Math.random() * 151) + 1)
      }
    },
    
  }
});

这是我试图打印随机口袋妖怪的家:


我想从前151个口袋妖怪中获取随机口袋妖怪,并使用Home组件中的控制台日志打印它
j8ag8udp

j8ag8udp1#

将您的代码更改为...

import { defineStore } from 'pinia'
import axios from 'axios'

let serverHost = 'https://pokeapi.co/api/v2'

export const pokeStore = defineStore("pokemons", {
  state: () => {
    return {
      pokemons: []
    };
  },
  actions: {
    async getOnePokemon() {
      try {
        let id = Math.floor(Math.random() * 151) + 1; // <- I have changed this...
        let response = await axios.get(`${serverHost}/pokemon/${id}`)
        if(response.data){
          response.data.name = response.data.name.replace('-', " ");
          let pokemon = {
            id: response.data.id,
            name: response.data.name,
            image: response.data.sprites.front_default
          }
          if(!pokemon.image){
            pokemon.image = response.data.sprites.front_shiny
          }
          return pokemon
        }
      } catch (error) {
        console.log(error)
      }
    },
    
  }
});

你在catch中有一些代码,试图做随机id,但那不是应该去的地方。
我更新了在函数中生成随机id,而不是传入id。

相关问题