【发布时间】: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