如何在nextjs中从两个不同的api路由获取数据



我使用的是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的返回道具应该是这样的: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

最新更新