nextjs:如何在本地路径上进行提取?

Mat*_*tte 3 typescript next.js

我想fetch在相对路径上使用该方法,例如:

export async function getServerSideProps() {
    // Fetch data from local API
    const res = await fetch(`/api/get_all_prices`)
    const data = await res.json()
    // Pass data to the page via props
    return { props: { data } }
}

function HomePage({props}) {
    return (
        // use props here
    )
}
Run Code Online (Sandbox Code Playgroud)

原因如下:我正在多台不同的计算机上测试我的代码,有时使用不同的端口

我希望这段代码能够在开发和生产环境中工作,以便必须记住在每台计算机/服务器的基础上更改使用的网址(女巫引入了许多不需要的潜在问题)

如何从本地 api 路由获取数据?

我无法弄清楚为什么该fetch方法不执行本地路由或​​解决方法。


[编辑]

解决方案是一个名为 superjson 的库。

我试图将我的代码放入 API 中,因为我无法将 getServerSideProps 与 prisma 一起正确使用(它返回无法在 JSON 中序列化的 Date 对象)

因此,我尝试使用 API 路径作为正确序列化的响应,但遇到了让我写这个问题的问题

完整的解决方案是将方法写入公共文件中(这允许分解),使用 lib superjson 正确序列化对象并在 getServerSideProps 方法中调用该方法

这允许与 nextjs 兼容的干净代码

amo*_*amo 6

您可以这样做,或者用可能导致错误的fetch('http://localhost:3000/api/get_all_prices') 变量替换基本 URL : 。但是,您应该只调用本地 API 进行测试,因为......fetch(baseUrl + 'api/get_all_prices')Only absolute paths are supported

您不应使用 fetch() 调用 getServerSideProps 中的 API 路由

文档中提到了这一点

建议直接在里面写你的逻辑getServerSideProps。这也适用于getStaticProps