为什么Node.js / Express不接受来自本地主机的连接?

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

我有这个代码(Express):

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本地主机,以确保它parsing为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 

怎么了?

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

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

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