agl*_*ier 4 reactjs next.js getserversideprops
有没有办法从多个 API 路由中获取数据getServerSideProps()?
我有一个表,我需要显示来自多个 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 } };
}
Run Code Online (Sandbox Code Playgroud)
我可能正在尝试一些愚蠢的事情,因此非常感谢指向正确方向的指针!!
luc*_*gas 11
您是否尝试过以下操作?
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 } };
}
Run Code Online (Sandbox Code Playgroud)
Promise.all 将触发两个请求,并在完成后返回两个 fetch 调用的解析值
| 归档时间: |
|
| 查看次数: |
2723 次 |
| 最近记录: |