我使用的是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)
}
发布于 2022-08-13 01:08:47
您可以做得更简单,我假设您不需要等待第一个请求结束才能启动第二个请求,所以您可以简单地使用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
,就像我在这里所做的那样。
https://stackoverflow.com/questions/73339756
复制