API 调用适用于 IPv4 地址 (127.0.0.1),但在使用 localhost 时收到“错误:连接 ECONNREFUSED ::1:3001”

问题描述 投票:0回答:3

所以我有一个非常简单的 API 调用,在我的前端使用 fetch 到

http://localhost:3001/test
,这给了我一个错误:
Error: connect ECONNREFUSED ::1:3001

但是,当我直接调用该 API(直接在浏览器中输入 api uri)时,它工作得很好。另外,当我在前端获取调用中将 localhost 更改为

http://127.0.0.1:3001/test
时,这也有效。

这似乎是一个网络错误,因为 ::1 和 127.0.0.1 解析为相同的地址,但一个是 IPv4,另一个是 IPv6,对吗?有人对为什么会这样有任何想法吗?

前端获取(BACKEND_URL = http://localhost:3001):

export async function getStaticProps() {
  const res = await fetch(`${BACKEND_URL}/explore`, {
    method: 'GET',
    headers: {
      "Content-Type": 'application/json',
      Origin: BASE_URL,
    },
  });

  ...
}

后端服务器监听端口 3001 (PORT = 3001):

const PORT = process.env.PORT;
app.listen(PORT, '0.0.0.0', () => {
    console.log(`Server is running on port ${PORT}`);
});

Stack:NextJS 前端、ExpressJS 后端、MongoDB Atlas DB、NextAuth 用于身份验证

express next.js network-programming ipv6 ipv4
3个回答
0
投票

可能有几个问题:

  1. 您需要将 IPv6 地址括在括号内,例如 http://[::1]:3001/test
  2. 该服务仅侦听 IPv4 地址,而不侦听 IPv6 地址。根据服务器的不同,您可能需要不同地配置监听地址

您的帖子未包含足够的信息,无法详细说明。请编辑您的帖子以包含实际的代码、服务和配置,以便我们可以为您提供进一步帮助。


0
投票

当您在后端 URL 中使用“localhost”时,默认情况下将解析为 IPv6 地址

::1
。但是,查看后端服务器代码,该后端正在侦听
0.0.0.0
,即 IPv4。

您需要让后端侦听 IPv6:

const PORT = process.env.PORT;
app.listen(PORT, '::', () => {
    console.log(`Server is running on port ${PORT}`);
});

0
投票

两个答案都指出了问题,您的服务器仅侦听 IpV4 ip,但您的“localhost”被转换为 IpV6

在 Mac/Linux 中检查映射的一种方法是检查 /etc/hosts 的内容,你会看到这样的内容:

##
# Host Database
#
# localhost is used to configure the loopback interface
# when the system is booting.  Do not change this entry.
##
127.0.0.1   localhost
255.255.255.255 broadcasthost
::1             localhost

最后一个 ip (::1) 是 localhost 的 IPv6 格式。 一个快速破解方法是从主机文件中注释 IPv6,并尝试是否可以解决问题(只需在该行的开头添加 # 即可):

127.0.0.1   localhost
255.255.255.255 broadcasthost
#::1             localhost

如果这解决了问题并且您仍然需要使用 IPv6,那么您必须检查服务器的配置(但有时我们无法控制服务器的配置方式,因此这可以解决问题)

© www.soinside.com 2019 - 2024. All rights reserved.