【问题标题】:Directly import next.js API endpoint in getServerSideProps()在 getServerSideProps() 中直接导入 next.js API 端点
【发布时间】: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(),
        }
    }
}

【问题讨论】:

  • 如果你给我更多关于你的项目设置的信息,特别是你的数据库,我可以完全为你解决问题并获得赏金;)

标签: reactjs next.js


【解决方案1】:

在任何情况下,您都必须将 reqres 对象传递给函数。但是如果你执行以下操作,post 属性应该填充一个NextApiResponse 实例,它的基础是一个stream.Writable 对象,这可能不是你想要的......

import { getPost } from './api/post';
...
export async function getServerSideProps({req, res}) {
  return {
    props: {
      post: await getPost(req, res),
    }
  }
}

您可以尝试读取流,但这似乎比重构代码更麻烦,但是如果您调用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),
    }
  }
}

【讨论】:

  • 感谢您的回复,我仍然有点不清楚如何在 getServerSideProps() 中获取 db 实例。您有函数“whereIsMyDb”,但是在处理中间件时,该函数将如何返回 db 实例?
  • 您使用的是哪个数据库,您是如何在您的应用中配置它的?
  • 问题是:为什么需要中间件来连接数据库?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-04-21
  • 2021-05-03
  • 1970-01-01
  • 1970-01-01
  • 2021-11-14
  • 2020-10-14
  • 2021-11-11
相关资源
最近更新 更多