【发布时间】:2022-04-10 13:47:45
【问题描述】:
我在 Vercel 部署工作流程中使用 Next.js,我正在按照 this 指南尝试在构建时设置页面生成。具体部分展示了以下基于外部 API 响应生成页面的示例:
// This function gets called at build time
export async function getStaticPaths() {
// Call an external API endpoint to get posts
const res = await fetch('https://.../posts')
const posts = await res.json()
// Get the paths we want to pre-render based on posts
const paths = posts.map(post => ({
params: { id: post.id },
}))
// We'll pre-render only these paths at build time.
// { fallback: false } means other routes should 404.
return { paths, fallback: false }
}
// This also gets called at build time
export async function getStaticProps({ params }) {
// params contains the post `id`.
// If the route is like /posts/1, then params.id is 1
const res = await fetch(`https://.../posts/${params.id}`)
const post = await res.json()
// Pass post data to the page via props
return { props: { post } }
}
我想完全做到这一点,但是我将我的 API 编写为同一代码存储库中的 Node.js 无服务器函数,它不是外部 API。
我尝试执行以下操作来调用我的 api:
// This function gets called at build time
export async function getStaticPaths() {
const res = await fetch('/api/get-designs');
const designs = await res.json();
// Get the paths we want to pre-render based on posts
const paths = designs.map(design => ({
params: { id: design.id },
}))
return {
// Only posts returned by api are generated at build time
paths: paths,
// Enable statically generating additional pages
fallback: true,
}
}
但是我得到一个错误,fetch api url 必须是绝对的。由于 Vercel 的部署方式,我不会总是有相同的部署 URL,所以我认为我不能在这里只使用硬编码的值。另外,我怀疑因为这个函数在构建时运行,所以我的函数还没有运行,因此不能被调用。我仍在尝试围绕这个 Next.js 静态生成的站点工作流程进行思考,但基本上我很困惑,因为它们似乎鼓励使用无服务器功能,以及用于页面生成的 getStaticPaths 方法,但它们似乎不起作用除非我错过了什么。
有没有一种方法可以让我在构建时运行我的 api 来获得这些结果?任何指导将不胜感激! 谢谢!
【问题讨论】:
标签: javascript node.js next.js serverless vercel