但后来我在 Next.js 文档中读到你不应该使用fetch()
到所有 API 路由getServerSideProps()
.
您想直接使用 API 路由中的逻辑getServerSideProps
,而不是调用您的内部 API。那是因为getServerSideProps
就像 API 路由一样在服务器上运行(从服务器向服务器本身发出请求是没有意义的)。您可以从文件系统读取或直接访问数据库getServerSideProps
。请注意,这仅适用于对内部 API 路由的调用 - 从以下位置调用外部 API 是完全可以的:getServerSideProps
.
来自 Next.jsgetServerSideProps https://nextjs.org/docs/basic-features/data-fetching/get-server-side-props#getserversideprops-or-api-routes文档:
当您想要获取数据时,很容易会尝试使用 API 路由
来自服务器的数据,然后调用该 API 路由getServerSideProps
。这是一种不必要且低效的方法,
因为这会导致因两者而提出额外的请求getServerSideProps
以及在服务器上运行的 API 路由。
(...) 相反,直接导入 API 路由中使用的逻辑
进入getServerSideProps
。这可能意味着调用 CMS、数据库或
直接从内部获取其他 APIgetServerSideProps
.
(注意使用时同样适用getStaticProps/getStaticPaths methods https://stackoverflow.com/a/66206394/1870780)
这是一个小的重构示例,允许您从 API 路由中重用逻辑getServerSideProps
.
假设您有这个简单的 API 路线。
// pages/api/user
export default async function handler(req, res) {
// Using a fetch here but could be any async operation to an external source
const response = await fetch(/* external API endpoint */)
const jsonData = await response.json()
res.status(200).json(jsonData)
}
您可以将获取逻辑提取到一个单独的函数中(仍然可以将其保留在api/user
如果你愿意的话),它仍然可以在 API 路由中使用。
// pages/api/user
export async function getData() {
const response = await fetch(/* external API endpoint */)
const jsonData = await response.json()
return jsonData
}
export default async function handler(req, res) {
const jsonData = await getData()
res.status(200).json(jsonData)
}
而且还允许您重复使用getData
函数于getServerSideProps
.
// pages/home
import { getData } from './api/user'
//...
export async function getServerSideProps(context) {
const jsonData = await getData()
//...
}