首页 > 解决方案 > having trouble chaining multiple axios request

问题描述

Ok, so what I am trying to do is do an axios.get() request pull specific data an id specifically, then use that id that I got to put it as a string literal so I can do my second request. I keep getting Info is not defined.

axios
  .get(
    `https://na1.api.riotgames.com/lol/summoner/v4/summoners/by-name/bloodstrive?api_key=${api}`
  )
  .then(response => {
    info = response.data.id;
  })
  .then(
    axios.get(
      `https://na1.api.riotgames.com/lol/league/v4/entries/by-summoner/${info}?api_key=${api}`
    )
  )
  .then(response => {
    summoner = response.data;
    return summoner;
  });
let getSummonerId = (req, res) => {
  res.status(200).send(summoner);
};
module.exports = {
  getSummonerId
};

标签: javascriptnode.jsreactjsaxios

解决方案


修复你的链接:

axios
  .get(
    `https://na1.api.riotgames.com/lol/summoner/v4/summoners/by-name/bloodstrive?api_key=${api}`
  )
  .then(response => {
    return response.data.id;
  })
  .then(info => {
    return axios.get(
      `https://na1.api.riotgames.com/lol/league/v4/entries/by-summoner/${info}?api_key=${api}`
    )
  })
  .then(response => {
    summoner = response.data;
    return summoner;
  });

就个人而言,我建议将 async 用于此类任务。使用 Promise 让处理事情变得更容易:

let fetchSummoner = async() => {
    const res = await axios.get(`https://na1.api.riotgames.com/lol/summoner/v4/summoners/by-name/bloodstrive?api_key=${api}`);

    const info = res.data.id;

    const res2 = await axios.get(`https://na1.api.riotgames.com/lol/league/v4/entries/by-summoner/${info}?api_key=${api}`);

    const summoner = res2.data;

    return summoner;
}

推荐阅读