node.js错误:连接ECONNREFUSED;来自服务器的响应 [英] node.js Error: connect ECONNREFUSED; response from server

查看:161
本文介绍了node.js错误:连接ECONNREFUSED;来自服务器的响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对这个小程序有问题:

I have a problem with this little program:

var http = require("http");
var request = http.request({
    hostname: "localhost",
    port: 8000,
    path: "/",
    method: "GET"
}, function(response) {
    var statusCode = response.statusCode;
    var headers = response.headers;
    var statusLine = "HTTP/" + response.httpVersion + " " +statusCode + " " + http.STATUS_CODES[statusCode];
    console.log(statusLine);
    for (header in headers) {
        console.log(header + ": " + headers[header]);
    }
    console.log();
    response.setEncoding("utf8");
    response.on("data", function(data) {
        process.stdout.write(data);
    });
    response.on("end", function() {
        console.log();
    });
});

控制台中的结果是:


events.js:141
      throw er; // Unhandled 'error' event
      ^

Error: connect ECONNREFUSED 127.0.0.1:8000
    at Object.exports._errnoException (util.js:870:11)
    at exports._exceptionWithHostPort (util.js:893:20)
    at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1063:14)

我不明白为什么会这样。

I do not understand why this happens.

推荐答案

从您的代码来看,您的文件似乎包含使获取对本地主机的请求(127.0.0.1:8000)。

From your code, It looks like your file contains code that makes get request to localhost (127.0.0.1:8000).

问题可能是您尚未在侦听端口8000的本地计算机上创建服务器。

The problem might be you have not created server on your local machine which listens to port 8000.

为此,您必须在可以满足您的请求的本地主机上设置服务器。

For that you have to set up server on localhost which can serve your request.


  1. 创建server.js

  1. Create server.js

var express = require('express');
var app = express();

app.get('/', function (req, res) {
  res.send('Hello World!'); // This will serve your request to '/'.
});

app.listen(8000, function () {
  console.log('Example app listening on port 8000!');
 });


  • 运行server.js:node server.js

  • Run server.js : node server.js

    运行文件,其中包含发出请求的代码。

    Run file that contains code to make request.

    这篇关于node.js错误:连接ECONNREFUSED;来自服务器的响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

  • 查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆