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

Is it possible to use API Routes for building pages in Next.JS getStaticProps/getStaticPaths?

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

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

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

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

You should not fetch an API route from getStaticProps — instead, you can write the server-side code directly in getStaticProps.

Note: You should not use fetch() to call an API route in getServerSideProps. Instead, directly import the logic used inside your API route. You may need to slightly refactor your code for this approach. Fetching from an external API is fine!

正如罗曼在他的回应中指出的那样,这样做并不理想。

但是,您可以利用 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 }; 
}