NextJS getServerSideProps() 具有多个获取请求 [英] NextJS getServerSideProps() with multiple fetch requests
问题描述
有没有办法在单个 getServerSideProps()
中从多个 API 路由中获取数据?
Is there a way to fetch data from multiple API routes in a single getServerSideProps()
?
我有一个表,我需要显示来自多个 MongoDB 集合的数据,并试图找出如何提取这些数据.
I have a table that I need to show data from multiple MongoDB collections and trying to figure out how to pull that data in.
本质上,我需要结合这两个功能,但似乎找不到最好的方法
Essentially, I need to combine these two functions but can't seem to find the best way to go about it
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 } };
}
我可能正在尝试一些愚蠢的事情,因此非常感谢指向正确方向的指针!!
I may be attempting something dumb so A pointer in the right direction is greatly appreciated!!
推荐答案
您是否尝试过以下操作?
Did you try the following?
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 调用的解析值
Promise.all
will trigger both requests and they will return the resolved value for both fetch calls when completed
这篇关于NextJS getServerSideProps() 具有多个获取请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!