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