我在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在构建时获取这些结果?任何指导将不胜感激! 谢谢!