当另一个 api 服务器也在本地主机中 运行 时,从 NextJs 应用程序的 gatServerProps 获取数据

Fetch data from gatServerProps of NextJs app when another api server is also running in localhost

根据 NextJs 文档:

You should not use fetch() to call an API route in getServerSideProps. Instead, directly import the logic used inside your API route. You may need to slightly refactor your code for this approach. Fetching from an external API is fine!

所以我们不能在 getStaticPropsgetServerSideProps 中使用 NextJs 内置的 APIs 但是当我要使用另一个基于 API 的服务时Laravel 框架作为后台服务器并通过 Axios 在 getServerSideProps 函数上获取它,我得到 Error: connect ECONNREFUSED 127.0.0.1:8080 错误。 还应该注意的是,如果 API 服务器在我们的开发机器之外寻址,一切都很好。换句话说,当它是开发环境并且Laravel后端服务器和NextJs前端服务器都位于localhost时会面临。

你能帮我找到解决这个问题的方法吗?

在 docker 容器内使用 localhost 或 127.0.0.1 时,它仅指向 docker 容器,而不是主机。

有两个非常简单的解决方案。

  1. 创建一个 docker 网络,将两个容器添加到其中,并使用容器名称而不是 ip (https://www.tutorialworks.com/container-networking/)
  2. 为此容器使用主机网络:https://docs.docker.com/network/host/

编辑:为有关如何创建和使用 docker 网络的教程添加了 link

因此,正如@tperamaki 的回答已经提到的:“在 docker 容器内使用 localhost 或 127.0.0.1 时,它仅指向 docker 容器,而不是主机。 “

您可以在本地网络中使用您机器的ip。例如,196.168.0.10:8080 而不是 127.0.0.1:8080.

但您也可以连接到特殊的 DNS 名称 host.docker.internal,它解析为主机使用的内部 IP 地址。 在您的情况下,只需添加其他容器正在侦听的端口:

http://host.docker.internal:8080

在文档的这一部分 Networking features in Docker Desktop for Mac, they explain how to connect from a container to a service on the host. Note that a mac is mentioned there, but I tried it on a linux distro and it also works (also in this other 中提到它适用于 windows)。