如何从 api 文件夹中获取 NextJS 中的 API

Posted

技术标签:

【中文标题】如何从 api 文件夹中获取 NextJS 中的 API【英文标题】:How to fetch an API in NextJS from the api folder 【发布时间】:2021-10-08 17:49:37 【问题描述】:

我在 API 文件夹中使用 NextJS 创建了一个 API。现在我想在 getServerSideProps 函数中从该 API 获取数据。

const res = await fetch(`localhost:3000/api/playlist`);

但我收到一条错误消息,说它只支持 HTTPS 协议。

Server Error

TypeError: Only HTTP(S) protocols are supported
This error happened while generating the page. Any console logs will be displayed in the terminal window.

如何从本地主机上的 NextJS API 获取数据? 感谢您的帮助!

【问题讨论】:

只是fetch('/api/playlist') @NikitaMazur 不幸的是,这不起作用,我收到 TypeError -> TypeError: Only absolute URLs are supported 可以分享一下代码吗? @NikitaMazur 我发现了问题,我忘了写“http://”。还是谢谢你 【参考方案1】:

我发现问题了,我忘了在网址前面加上http://

代码将如下所示:

const res = await fetch(`http://localhost:3000/api/playlist`);

【讨论】:

以上是关于如何从 api 文件夹中获取 NextJS 中的 API的主要内容,如果未能解决你的问题,请参考以下文章