2017-02-07 19 views
0

静的ファイルのロード要求を送信しようとするとNodejsエラーECONNREFUSED 127.0.0.1:3000が発生しました。私はこのエラーに関する多くの質問を見たことがありますが、明らかにこのエラーがなぜスローされるのかについてはまっすぐな答えはありません。以下は、私のコードです。私はlocalhostを127.0.0.1に変更しようとしましたが、ポート番号を3000,7000,8080に変更しましたが、何も解決しませんでした。誰かに助言してもらえますか?ありがとうございました。エラー:ECONNREFUSEDを接続してください。 Unhandled 'error'イベントNodeJS

//Basic web client retrieving content of file using get request 

var http = require('http'); 

//options for request 

var options = { 

hostname: 'localhost', 
port: '3000', 
path: '../html/hello.html' 

}; 

//function to handle response from request 

    function getResponse(response){ 

    var serverData=''; 

    response.on('data', function(chunk){ 

    serverData += chunk; 
    }); 

    response.on('end', function(){ 

     console.log(serverData); 
    }); 
}; 

    http.request(options, function(response, error){ 

    getResponse(response); 

}).end(); 

答えて

3

お客様のクライアントコードで十分です。特定のポート番号をリッスンしているサーバーがなく、サーバーがデータを送信しておらず、サーバーからデータを取得して蓄積しようとしているため、ECONNREFUSEDが表示されます。ここで

はサンプルコードです:

//Requesting for http and fs modules 
var http = require('http'); 
var fs = require('fs'); 

//creating the server and reading the file synchronously 
var server = http.createServer(function(req, res) { 
    res.end(fs.readFileSync('./html1.html')); 
}).listen(3000); 

//creating the client which connects to local host at port number 3000 
var options = { 
    hostname: 'localhost', 
    port: '3000', 
} 

//getting the data from server, storing it in to a variable, and printing at end of the data 
function getResponse(response){ 
    var serverData=''; 
    response.on('data', function(chunk){ 
      serverData += chunk; 
    }); 
response.on('end', function(){ 
      console.log(serverData); 
    }); 
}; 

http.request(options, function(response, error){ 
    getResponse(response); 
}).end(); 
+0

ありがとうございます。残念ながら、私がNodeを学ぶために使っているリソースは、サーバを事前に起動しておく必要があることを指摘しませんでした。ありがとう – Celaro

0

エラーが処理されていないというコードの問題点があります。このためには、まずエラーを処理する必要があります。

+0

それはエラーイベントが処理されないことを言いますが、あなたが言ったように、私はエラーを処理した場合でも、私はまだ同じエラーメッセージとECONNREFUSED 127.0.0.1を持っています:3000はまだそこにあります。 – Celaro

+0

は、別のインスタンスが実行されていた場合に問題になる可能性があります。端末 'netstat -tulpn'でこのコマンドを実行した後、ポート番号を確認してプロセスを終了します。すなわちprocess_idを殺す。その後は正常に再開する必要があります。 –

+0

コマンドps aux | grepノードは、ノードインスタンスがkillを実行していないことを示します。これは、エラーがノードの実行中のインスタンスに関連していないことを意味します。 @ Shekar Tyagi私はそれが動作するように絶対upvoteします! – Celaro

関連する問題