2016-01-24 137 views
0

當我運行app.js,我得到這個錯誤:Node.js的自定義模塊

MBPdiDaniele3:Desktop danielemartini$ node app.js 
events.js:141 
     throw er; // Unhandled 'error' event 
    ^

Error: connect ECONNREFUSED 127.0.0.1:8080 
    at Object.exports._errnoException (util.js:870:11) 
    at exports._exceptionWithHostPort (util.js:893:20) 
    at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1063:14) 
MBPdiDaniele3:Desktop danielemartini$ 

下面的代碼爲make_request.js

var http = require('http'); 

var makeRequest = function(message) { 

    var options = { 
     host: 'localhost', port: 8080, path:'/', method: 'POST' 
    } 

    var request = http.request(options, function(response) { 
     response.on('data', function(data) { 
      console.log(data); 
     }); 
    }); 
    request.write(message); 
    request.end(); 
}; 
module.exports = makeRequest; 

下面的代碼爲app.js

var makeRequest = require('./make_request'); 

makeRequest("Here's looking at you, kid"); 
makeRequest("Hello, this is dog"); 
+2

而......你的問題是什麼? – usandfriends

+1

也許這是因爲您沒有任何東西在端口8080上偵聽。 – usandfriends

+0

確保沒有其他服務正在運行端口8080(Tomcat或您的服務的早期版本) – xaviert

回答

1

有幾種可能的原因:

  1. 沒有服務在本地主機上運行:8080
  2. 服務8080運行其主動拒絕連接。

要查看正在運行什麼,使用這些2個的命令之一(UNIX):

  • lsof -i :8080 -S
  • netstat -a | grep 8080

3 - 你正在運行的服務不會綁定到您的內部IP。

我在雲服務器上遇到過幾次問題,其中localhost/127.0.0.1無法識別。嘗試使用機器的外部IP(並確保防火牆允許您發出請求),或強制您的服務綁定到所有接口。

希望它有幫助。

+0

這不是一個答案,這是猜測和一般調試指令 –

+0

@Jarrod_Roberson:這可能不是答案,但它是有益的,因此有用。 – chriskelly

+0

@JarrodRoberson不是幫助用戶堆棧溢出?這個問題有三種可能的答案,並且遵循我的信息應該有助於OP解決他的問題。如果有的話,這個問題可能需要重寫,包括'我試過這個和那個',因此刪除了猜測元素。 – xShirase