链接多个axios请求时遇到问题

时间:2019-05-19 11:28:16

标签: javascript node.js reactjs axios

好吧,所以我想做的是做一个axios.get()请求来提取特定数据的id,然后使用我把它当作字符串文字的那个id,以便我可以做第二个请求。我不断收到未定义的信息。

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
};

2 个答案:

答案 0 :(得分:3)

修复链接:

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;
  });

就个人而言,我建议对此类任务进行异步处理。凭承诺使处理事情变得更加容易:

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;
}

答案 1 :(得分:0)

在当前代码中,您尚未在第二个axios请求中添加return语句。否则,将不会获取并返回第二个URL。 请尝试以下代码。

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;
  });