【问题标题】:How to call a serverless function in Next.js getStaticPaths [duplicate]如何在 Next.js getStaticPaths 中调用无服务器函数 [重复]
【发布时间】: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


    【解决方案1】:

    在这种情况下,我们可以将服务器逻辑提取到一个函数中,并且该函数可以直接在您的 api 路由文件中使用。因此,对于 CR,我们可以使用 /api/whateverRoute 并在 getStaticPaths 中直接使用该函数本身。

    【讨论】:

      猜你喜欢
      • 2023-02-03
      • 2020-12-18
      • 2020-12-18
      • 2021-05-03
      • 2022-06-23
      • 2021-12-05
      • 2022-01-26
      • 2018-03-09
      • 1970-01-01
      相关资源
      最近更新 更多