在 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;
Run Code Online (Sandbox Code Playgroud)
将 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(),
});
});
Run Code Online (Sandbox Code Playgroud)
然后在我的 next.js 页面中:
import { getPost } from './api/post';
...
export async function getServerSideProps(context) {
return {
props: {
post: getPost(),
}
}
}
Run Code Online (Sandbox Code Playgroud)
无论如何,您都必须将req和res对象传递给该函数。但是如果你执行以下操作,post道具应该填充一个NextApiResponse实例,它的基础是一个stream.Writable对象,这可能不是你想要的......
import { getPost } from './api/post';
...
export async function getServerSideProps({req, res}) {
return {
props: {
post: await getPost(req, res),
}
}
}
Run Code Online (Sandbox Code Playgroud)
您可以尝试读取流,但这似乎比重构代码更麻烦,但如果您调用getPost(req, res).end(),我认为您应该获取流数据,但我不确定它将如何格式化。你必须检查一下。
您可以将您的功能再拆分一些..
// In your api endpoint:
const handler = nextConnect();
handler.use(middleware);
export async function getPostMethod(db) {
return await db.collection("posts").findOne();
}
handler.get(async (req, res) => {
res.send({
post: await getPostMethod(req, res, req.db)
})
});
export default handler;
// In your page component:
export async function getServerSideProps({req, res}) {
// Do what ever you have to do here to get your database connection
const db = await whereIsMyDb()
return {
props: {
post: await getPostMethod(db),
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3129 次 |
| 最近记录: |