Javascript 如何在Next.js GetStaticPath中调用无服务器函数
我将Next.js与Vercel部署工作流一起使用,我将按照指南在构建时尝试和设置页面生成。特定部分显示了以下基于外部API响应生成页面的示例:Javascript 如何在Next.js GetStaticPath中调用无服务器函数,javascript,node.js,next.js,serverless,vercel,Javascript,Node.js,Next.js,Serverless,Vercel,我将Next.js与Vercel部署工作流一起使用,我将按照指南在构建时尝试和设置页面生成。特定部分显示了以下基于外部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
// 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 } }
}
我想准确地做到这一点,但是我在同一个代码库中以Node.js serverless函数的形式编写了API,它不是一个外部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静态生成的站点工作流,但基本上我感到困惑,因为它们似乎鼓励使用无服务器功能,以及用于页面生成的getstaticpath
方法,但它们似乎无法协同工作,除非我遗漏了什么
有没有一种方法可以在构建时运行api来获得这些结果?任何指导都将不胜感激!
谢谢