node.js 错误:连接 ECONNREFUSED;来自服务器的响应

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

本文介绍了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();
    });
});

The result in console is this:

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.

解决方案

From your code, It looks like your file contains code that makes get request to localhost (127.0.0.1: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. 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!');
     });
    

  2. Run server.js : node server.js

  3. Run file that contains code to make request.

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

本文标题为:node.js 错误:连接 ECONNREFUSED;来自服务器的响应

基础教程推荐