微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

是否可以使用 API 路由在 Next.JS getStaticProps/getStaticPaths 中构建页面?

如何解决是否可以使用 API 路由在 Next.JS getStaticProps/getStaticPaths 中构建页面?

我正在使用 MongoDB 制作静态 Next.JS 应用程序。

在我的静态 Next.JS 应用程序中,我可以使用 api 路由来构建页面吗?例如,在getStaticProps中使用GET方法获取产品?或者这是不好的方法

现在我使用文档中的经典方式(直接调用数据库,如 find 等)。

提前感谢您的帮助!

解决方法

您可能可以,但将 getStaticProps/getStaticPaths 中的 API 路由用作 stated in the docs 是一种不好的做法。

您不应从 getStaticProps 获取 API 路由 — 相反,您可以直接在 getStaticProps 中编写服务器端代码。

注意:您不应该使用 fetch() 在 getServerSideProps 中调用 API 路由。相反,直接导入 API 路由中使用的逻辑。您可能需要为这种方法稍微重构您的代码。 可以从外部 API 获取数据!

,

Roman 在他的回复中指出,这样做并不理想。

但是,您可以利用 getStaticProps 从数据库中获取所需的文档。如果您正在动态呈现使用配置文件的经典用例,那么它可能看起来像以下伪代码,并假设您有某种 Model 来连接您的MongoDB:

// under app/pages/users/[userId].js

import UserProfile from 'components/user-profile';
import User from 'models/user';

export default UserProfile;

// both at request time and build time,preps the props passed to the UserProfile component.
export const getStaticProps = async ({params}) => {
  const user = await User.find(params.id);
  return { 
    props: { user }
  }
}

额外奖励:如果您的用例支持它,那么将其转换为静态生成的站点非常简单:

// instructs next to render all user profiles using SSG
export const getStaticPaths = async () => {
  const users = await User.findAll();
  const paths = users.map(user => `/users/${user.id}`);
  return { paths,fallback: false }; 
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。