【发布时间】:2020-12-30 10:33:59
【问题描述】:
在 Next.js 中使用 getServerSideProps() 获取数据时,他们建议直接导入 API 端点,而不是使用 fetch() 并运行另一个 HTTP 请求。这是有道理的,在为我的 API 实现中间件之前,我能够让它工作(注意,我正在使用 Next.js 中内置的 API 功能)。现在实现了中间件,我不能导出使用中间件的函数,我必须导出处理程序。见下文:
const handler = nextConnect();
handler.use(middleware);
handler.get(async (req, res) => {
const post = await req.db.collection("posts").findOne();
res.send({
post: post,
});
});
export default handler;
将我的 API 端点导入 getServerSideProps 的推荐方法是什么?我想做如下操作,但是getPost()函数不再访问数据库中间件:
export const getPost = async () => {
const post = await req.db.collection("posts").findOne();
return post;
}
handler.get(async (req, res) => {
res.send({
post: getPost(),
});
});
然后在我的 next.js 页面中:
import { getPost } from './api/post';
...
export async function getServerSideProps(context) {
return {
props: {
post: getPost(),
}
}
}
【问题讨论】:
-
如果你给我更多关于你的项目设置的信息,特别是你的数据库,我可以完全为你解决问题并获得赏金;)