【问题标题】:Pokemon API fetch (axios) data then render all the data issuePokemon API 获取(axios)数据然后呈现所有数据问题
【发布时间】:2022-01-20 18:58:47
【问题描述】:

我对前端和后端开发相当陌生。尝试使用 React / Node.js 构建一个小型网络,尝试从 Pokemon API 获取数据:https://pokeapi.co/

我正在尝试获取(使用 axios)所有口袋妖怪的 ID、名称、类型、图片然后渲染它。我取回了所有数据,但是在渲染它时,它只能渲染第一个数据。有错误信息

Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
    at new NodeError (node:internal/errors:371:5)
    at ServerResponse.setHeader (node:_http_outgoing:576:11)
    .....

代码:

router.get('/', async function (req, res, next) {
  const pokemonUrl = 'https://pokeapi.co/api/v2/pokemon?limit=10';
  var pokemonPic = [];
  var pokemons = [];
  // a nest fetch (aixos) data
  await axios({
    method: 'get',
    url: pokemonUrl,
    timeout: 10000
  })
    .then((all) => {
      // store data and give access for all
      let { data } = all;
      // fetch pokemon infomation from each url
      data.results.forEach(function (pokemon) {
        // the second url to fecth data
        const urll = pokemon.url;
        axios({
          method: 'get',
          url: urll,
          timeout: 10000
        })
          .then((respon) => {
            // otherwise have no access to respon
            let { data } = respon;
            var pokeTypes = [];
            let pokeName = data.name;
            let pokeID = data.id;
            let pokePic = data.sprites.front_default;
            // pokemon types
            for (var i = 0; i < data.types.length; i++) {
              pokeTypes += data.types[i].type.name + ' '
            }
            // check the outcome
            console.log(pokeID, pokeName, pokeTypes, pokePic);
            // render index from view

            res.render('index', {
              pokePic,
              name: pokeName,
              pokeTypes: pokeTypes,
              pokeID
            })
            // return pokeID, pokeName, pokeTypes, pokePic;
          })
          .catch((error) => {
            console.log(error);
          })
      })
    })

任何提示都会有所帮助。 热烈感谢。

【问题讨论】:

  • 有大量图片返回,查看返回的sprites属性下
  • 我明白了,非常感谢

标签: node.js api axios fetch-api pokemon-go


【解决方案1】:

您可以使用以下方法访问口袋妖怪的图像:

        const getPokemon = async (pokemonName) => {
          await axios.get(`https://pokeapi.co/api/v2/pokemon/${pokemonName}`).then(response => {
return response.data.sprites.front_default
}).catch(err => console.log(err))
    }
getPokemon('pikachu')

你应该得到这个:

【讨论】:

  • 谢谢。我把这个整理好了。想到了另一个问题。我正在尝试获取(使用 axios)所有口袋妖怪的 ID、名称、类型、图片然后渲染它。我取回了所有数据,在渲染它时,它只能渲染第一个获取的数据。带有错误消息 Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client at new NodeError (node:internal/errors:371:5) at ServerResponse.setHeader (node:_http_outgoing:576:11) .....
猜你喜欢
  • 2020-10-16
  • 1970-01-01
  • 1970-01-01
  • 2021-03-11
  • 2021-09-22
  • 2019-06-27
  • 1970-01-01
  • 1970-01-01
  • 2020-12-17
相关资源
最近更新 更多