【问题标题】:How to display all successful and unsuccessful request to an API in Next.js?如何在 Next.js 中显示对 API 的所有成功和不成功请求?
【发布时间】:2021-11-24 19:36:32
【问题描述】:

我有一个输入,通过逗号 Ricky、Marty 等写下角色的名字。

因此,我对每个英雄都在数据库中提出请求并显示结果。

如果找不到英雄,我如何显示成功和不成功请求的列表?

export const getServerSideProps: GetServerSideProps = async (context) => {

  const { name } = context.query;
  const nameArray = (name as string).split(',');

  const allRequest = nameArray.map((el) => axios.get(`https://rickandmortyapi.com/api/character/?name=${el}`));

  const charactersList = await axios.all(allRequest)
    .then(axios.spread((...response) => response.map((e) => e.data.results)));

  return ({
    props: {
      charactersList,
    },
  });
};

使用这段代码,我只需从数据库中获取数据。我需要它

Ricky(来自输入的数据)---来自数据库的数据 Morty(来自输入的数据---来自数据库的数据)

等,但未找到列表。

【问题讨论】:

    标签: reactjs axios next.js


    【解决方案1】:

    您可能希望使用Promise.allSettled() 等待所有承诺解决或拒绝(如果其中一个拒绝,请避免拒绝所有内容)。

    export const getServerSideProps: GetServerSideProps = async (context) => {
        const { name } = context.query;
        const nameArray = Array.isArray(name) ? name : [name];
    
        const allRequest = nameArray.map((el) =>
            axios.get(`https://rickandmortyapi.com/api/character/?name=${el}`)
        );
    
        const charactersList = await Promise.allSettled(allRequest).then((res) => {
            // Iterate over all results, both successful or unsuccessful
            return res.map((result) => {
                // Returns response data if successful, or `undefined` otherwise
                // Handle this however you like
                return result.value?.data.results;
            });
        });
       
        //...
    }
    

    请注意,您应该避免使用axios.all/axios.spread,因为它们一直是deprecated

    【讨论】:

      猜你喜欢
      • 2021-11-15
      • 2020-05-24
      • 2021-05-20
      • 2020-04-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-09
      • 1970-01-01
      相关资源
      最近更新 更多