簡體   English   中英

如何從 nextjs 中的兩個不同的 api 路由獲取數據?

[英]How to get data from two different api routes in nextjs?

我正在使用 Next.js 並且我需要從兩個不同的 API 路由獲取數據。 我想在getServerSideProps中獲取數據。

我需要的第一個數據來自http://localhost:3000/api/admin/classes/${className}路由。

第二組數據將來自http://localhost:3000/api/admin/classes/${className}/subjects這個路由。

當我嘗試從單個 API 獲取數據時,它工作正常。 我嘗試使用 getServerSideProps 中的代碼從 API 中獲取數據。 但它不起作用。

我想要這樣的數據export default function classPage({ subjects, classDetail }) {} gerServerSideProps 的返回 props 應該如下所示: return { props: {classDetail: data, subjects: data2} } ,如果可能的話

export async function getServerSideProps({ query: { className } }) {
  const res = await fetch(
    `http://localhost:3000/api/admin/classes/${className}`
  ).then(() => {
    const res2 = await fetch(`http://localhost:3000/api/classes/${className}/subjects`)
  });
  const { data } = await res.json();
  const {data2} = await res2.json()

  return { props: { classDetail: data } };
}

Api 獲取請求碼:

      try {
        const subjectDetail = await Subject.find({}).populate('classDetail')
        res.status(200).json({success: true, data: subjectDetail})
      } catch (error) {
        res.status(400).json({success: false})
        console.log(error)
      }

你可以做的更簡單,我假設你不需要等待第一個請求結束來開始第二個請求,所以你可以簡單地使用Promise.all來等待兩個請求完成。

export async function getServerSideProps({ query: { className } }) {
  // Create the promises for the data we need to fetch
  const promises = [
    fetch(`http://localhost:3000/api/admin/classes/${className}`).then(res => res.json()),
    fetch(`http://localhost:3000/api/classes/${className}/subjects`).then(res => res.json()),
  ];

  // Wait for all the promises to resolve and get the data
  const [classDetail, subjects] = (await Promise.all(promises)).map(p => p.data);

  return { props: { classDetail, subjects } };
}

但是第二個請求似乎遇到的問題是,當您編寫: const {data2} = await res2.json()時,您試圖從響應中獲取屬性data2 ,這可能不是您想要的。 您需要像我在這里所做的那樣從兩個響應中獲取data

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM