簡體   English   中英

錯誤:連接ECONNREFUSED。 未處理的“錯誤”事件NodeJS

[英]Error: connect ECONNREFUSED. Unhandled 'error' event NodeJS

我在嘗試發送獲取請求以加載靜態文件時遇到Nodejs錯誤ECONNREFUSED 127.0.0.1:3000。 我已經看到很多有關此錯誤的問題,但是顯然沒有直接的答案可以解釋為什么會引發此錯誤。 下面是我的代碼。 我嘗試將localhost更改為127.0.0.1或更改端口號3000、7000、8080,但沒有任何解決方案。 有人可以建議嗎? 謝謝。

//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();

您的客戶端代碼足以正常工作。 之所以得到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();

代碼中的問題是您沒有處理錯誤,為此您必須首先處理錯誤。

var http = require('http');
    var options = {
    hostname: 'localhost',
    port: '3000',
    path: '../html/hello.html'
    };
      function getResponse(response){
    var serverData='';

      response.on('data', function(chunk){
         serverData += chunk;
      });

       response.on('end', function(){
    console.log(serverData);
       });
     };

      http.request(options, function(error , response){
    if(error){
    console.log(error);//handle error here.
    }else{
      getResponse(response);
    }}).end();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM