node.js - 错误 : connect ECONNREFUSED. 未处理的 'error' 事件 NodeJS

标签 node.js

当我尝试发送获取请求以加载静态文件时,遇到 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();

关于node.js - 错误 : connect ECONNREFUSED. 未处理的 'error' 事件 NodeJS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42093966/

相关文章:

javascript - 在循环内运行 Node.js 的 fs.rename() 时出错

node.js - 随着时间的推移, Node 应用程序逐渐消耗内存

node.js - Azure DevOps Pipeline 中的 Docker 镜像中的单元测试

javascript - mongoose.save 的问题永远不会在 promise 内返回

node.js - Cognito 身份验证后自定义响应

node.js - 将现有 Nodejs Express 应用程序转换为 aws 无服务器应用程序

node.js - 世博会启动后崩溃

angularjs - Angular/Node/Express/Passport 跨域问题 - 启用 CORS Passport Facebook 身份验证

node.js - 使用 Speech-to-Text API 无法解决 "Requested entity was not found"错误

node.js - 如何将预处理器绑定(bind)到 babel-register,以便在 babel 启动之前修改文件