2016-11-09 57 views
1

我今天遇到這種奇怪的行爲,我找不到原因。我正在使用MacOS Sierra。爲什麼Node.js/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 

我檢查了我的hosts文件:

$ 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本地主機,以確保它解析爲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 

現在我試着給我們反而瞧,它的作品?

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

怎麼了?

+0

你介意發佈/ etc/hosts文件的內容嗎?在我看來,'localhost'可能被錯誤地映射到那裏。這可能會導致這種錯誤。 –

+0

您的網絡適配器是否啓用了IPv6? Curl可能試圖通過IPv6連接,但服務器不在該地址上進行監聽。 –

+0

添加主機文件 – mitchkman

回答

2

cURL正試圖通過IPv6連接,但您的Express服務器正在監聽127.0.0.1這是IPv4。

您可以強制cURL通過IPv4與-4選項進行連接。

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

謝謝!這是問題! – mitchkman