【问题标题】:How can I fetch data from the host URL in getStaticPaths() in Next.js serverless function?如何在 Next.js 无服务器函数中从 getStaticPaths() 中的主机 URL 获取数据?
【发布时间】:2023-02-03 02:04:39
【问题描述】:

我有一个 Next.js 应用程序,它使用无服务器函数从其主机获取数据。主机 URL 存储在 .env 文件中,对于开发设置为 http://localhost:3000/api/data,对于生产设置为 https://productionurl.com/api/data。但是,出于测试目的,我将应用程序托管在 Vercel 上,测试 URL 将随机生成,例如https://randomvercelurl_abcd1234.com/api/data

我可以在 getServerSideProps 方法中使用 ctx 或 req 获取主机 URL,如下面的示例代码所示:

export async function getServerSideProps({query, req}){
    const API_URL = req.protocol + req.headers.host + "/api/data"
    const res = await axios.get(API_URL)
 ...
}

问题出现在getStaticPaths 方法中,我需要在该方法中获取数据以生成动态路由。我没有办法在此方法中获取主机 URL,如以下示例代码所示:

export async function getStaticPaths() {
    const host = ???
    const res = await fetch(`${host}/api/data`)
    const posts = await res.json()

    const paths = posts.map((post) => ({
        params: { id: post.id },
    }))

    return { paths, fallback: false }
}

如何访问 getStaticPaths 方法中的主机 URL 来获取数据?

【问题讨论】:

    标签: reactjs next.js server-side-rendering next-router


    【解决方案1】:

    您无法使用 host 获得上下文,例如 getServerSideProps,因为 getStaticPaths 在构建时运行。因此,您要从中获取数据的 URL 应该在代码中或通过环境变量完全已知。

    getStaticPaths 只会在生产构建期间运行,不会在运行时调用。您可以验证在 getStaticPaths 中编写的代码是否已从客户端包 with this tool 中删除。

    您可能还想阅读when should I use getStaticPaths?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-06-23
      • 2020-07-03
      • 2020-06-08
      • 2019-07-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多