【问题标题】:NextJS getServerSideProps() with multiple fetch requestsNextJS getServerSideProps() 具有多个获取请求
【发布时间】:2021-04-09 06:29:53
【问题描述】:

有没有办法在单个 getServerSideProps() 中从多个 API 路由中获取数据?

我有一个表,我需要显示来自多个 MongoDB 集合的数据,并试图弄清楚如何将这些数据拉入。

基本上,我需要将这两个功能结合起来,但似乎找不到最好的方法。

export async function getServerSideProps() {
  const res = await fetch(`${process.env.APP_DOMAIN}/api/${apiRoute}`);
  const { data } = await res.json();
  return { props: { operations: data } };
}

export async function getServerSideProps() {
  const res = await fetch(`${process.env.APP_DOMAIN}/api/${apiRoute2}`);
  const { data } = await res.json();
  return { props: { incidents: data } };
}

我可能正在尝试一些愚蠢的事情,因此非常感谢指向正确方向的指针!

【问题讨论】:

    标签: javascript reactjs next.js


    【解决方案1】:

    您是否尝试过以下操作?

    export async function getServerSideProps() {
      const [operationsRes, incidentsRes] = await Promise.all([
        fetch(`${process.env.APP_DOMAIN}/api/${apiRoute}`), 
        fetch(`${process.env.APP_DOMAIN}/api/${apiRoute2}`)
      ]);
      const [operations, incidents] = await Promise.all([
        operationsRes.json(), 
        incidentsRes.json()
      ]);
      return { props: { operations, incidents } };
    }
    

    Promise.all 将触发两个请求,完成后它们将返回两个 fetch 调用的解析值

    【讨论】:

    • 做到了,感谢您的快速回答!我对此还很陌生,我知道我必须更多地研究 Promises。
    • 我使用的模式相同,但它会降低页面性能。
    • API 的性能如何?我认为这种模式比顺序执行要好得多
    猜你喜欢
    • 2020-07-25
    • 2021-05-23
    • 2021-09-04
    • 2021-12-31
    • 2021-10-08
    • 1970-01-01
    • 2021-05-15
    • 2021-11-17
    • 1970-01-01
    相关资源
    最近更新 更多