【问题标题】:Why does Node.js/Express not accept connections from localhost?为什么 Node.js/Express 不接受来自 localhost 的连接?
【发布时间】:2016-11-09 23:57:24
【问题描述】:

我今天遇到了这种奇怪的行为,我找不到原因。我正在使用 MacOS Sierra。

我有这个代码(快递):

app.server.listen(config.port, config.address, function () {
    logger.info('app is listening on', config.address + ':' + config.port);
});

它会打印出来

app is listening on 127.0.0.1:5000

但是,如果我尝试curl,它会失败。

$ curl http://localhost:5000/api/ping
curl: (56) Recv failure: Connection reset by peer

我检查了我的主机文件:

$ cat /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

所以我 ping localhost 以确保它解析为 127.0.0.1:

$ ping localhost
PING localhost (127.0.0.1): 56 data bytes
64 bytes from 127.0.0.1: icmp_seq=0 ttl=64 time=0.061 ms
64 bytes from 127.0.0.1: icmp_seq=1 ttl=64 time=0.126 ms
64 bytes from 127.0.0.1: icmp_seq=2 ttl=64 time=0.135 ms
^C
--- localhost ping statistics ---
3 packets transmitted, 3 packets received, 0.0% packet loss
round-trip min/avg/max/stddev = 0.061/0.107/0.135/0.033 ms

我再试一次,但失败了

$ curl http://localhost:5000/api/ping
curl: (56) Recv failure: Connection reset by peer

现在我尝试改用127.0.0.1,瞧,它有效吗?

$ curl http://127.0.0.1:5000/api/ping
pong

怎么了?

【问题讨论】:

  • 您介意发布您的 /etc/hosts 文件的内容吗?在我看来,localhost 可能在那里被错误地映射。这可能会导致此类错误。
  • 您的网络适配器是否启用了 IPv6? Curl 可能正在尝试通过 IPv6 进行连接,但服务器并未监听该地址。
  • 是的,我的网络适配器启用了 IPv6,查看 ifconfig
  • 尝试在 curl 命令中使用选项-4
  • 是的,现在可以使用$ curl -4 http://localhost:5000/api/ping pong

标签: node.js express networking


【解决方案1】:

cURL 正在尝试通过 IPv6 连接,但您的 Express 服务器正在侦听 IPv4 的 127.0.0.1。

您可以使用 -4 选项强制 cURL 通过 IPv4 连接。

curl -4 http://127.0.0.1:5000/api/ping

【讨论】:

  • 非常感谢!这就是问题所在!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-09-25
  • 1970-01-01
  • 2022-01-19
  • 1970-01-01
  • 2011-07-09
  • 2019-03-01
相关资源
最近更新 更多