当我尝试发送 get 请求以加载静态文件时,我遇到了 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();
Run Code Online (Sandbox Code Playgroud)
您的客户端代码足以工作。您收到 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();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7091 次 |
| 最近记录: |