为什么Node.js / Express不接受来自localhost的连接?

时间:2016-11-09 23:57:24

标签: node.js express networking

今天我遇到了这种奇怪的行为,我找不到原因。我正在使用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 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

怎么了?

1 个答案:

答案 0 :(得分:2)

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

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

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