43

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.

aynber
  • 22,380
  • 8
  • 50
  • 63
Marco Ghieri
  • 439
  • 1
  • 4
  • 3
  • What do you want to achieve with the code? – gnerkus Feb 04 '16 at 11:19
  • That happens because it could not connect to the endpoint - in this case `http://localhost:8000` is not reachable – charliebrownie Feb 04 '16 at 11:21
  • Are you supposed to have something running on localhost:8000? Because it doesn't look like you do right now. – philnash Feb 04 '16 at 11:26
  • trying with other programs is reached. Port 8000 is free – Marco Ghieri Feb 04 '16 at 12:00
  • @MarcoGhieri what do you mean by _free_? There's nothing listening on it? That would explain the error. – robertklep Feb 04 '16 at 13:42
  • I had the same problem, not sure why I couldn't get a response from the server. The answer is in "Promise" For my situation, 1. I checked from cli that node is listening on my port 2. I was able to use curl to make a request to it and it was all good. 3. The problem was when I use the "request" module, it ran it before the server could get back to me, so I downloaded 'request-promise' and that solved the problem. This is not an answer but for those who have been searching, you can see if the async, sync thing is your hint. – Rex May 10 '17 at 17:56
  • I am facing the same issue and the reason is that my node program is calling one rest api. I get this error if that rest api is not accessible. Can someone tell me how to handle that exception, because it crashes my node server which i want to avoid. – Devesh M May 16 '18 at 12:19
  • I get the same when using mysql2 or mysqljs node library – landrykapela Dec 18 '19 at 17:27
  • I was running node 17 (on a M1 Mac) and I removed it via `brew uninstall node` and then install node 16 with `brew install node@16`. Worked a treat. I _may_ have had to `brew link --force node@16` but I can't remember right now. – Joshua Pinter Jan 22 '22 at 02:21

10 Answers10

46

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.

Andrey Tsarev
  • 769
  • 1
  • 8
  • 25
Piyush Sagar
  • 2,931
  • 23
  • 26
  • 5
    NB. As as a general rule processes running without root privileges cannot bind to ports below 1024. – Rocco Musolino Jun 15 '17 at 10:31
  • 1
    @RoccoMusolino answer above worked for me. After fighting with this error for a whole day on an iMac, `sudo` did the trick! I wonder where node or iOS`(putting this here for web crawler)` was getting `127.0.0.1:80` Even with all proxy settings disabled, I still got this error – Jonathan Kibet Feb 20 '20 at 15:04
18

Please use [::1] instead of localhost, and make sure that the port is correct, and put the port inside the link.

const request = require('request');

   let json = {
        "id": id,
        "filename": filename
    };
    let options = {
        uri: "http://[::1]:8000" + constants.PATH_TO_API,
        // port:443,
        method: 'POST',
        json: json
    };
    request(options, function (error, response, body) {
        if (error) {
            console.error("httpRequests : error " + error);
        }
        if (response) {
            let statusCode = response.status_code;
            if (callback) {
                callback(body);
            }
        }
    });
Ahmad Zahabi
  • 1,110
  • 12
  • 15
2

I solved this problem with redis-server, you can install that like this!

sudo apt-get install redis-server

after that see the port and change it!

Lee Taylor
  • 7,761
  • 16
  • 33
  • 49
1

I had the same problem on my mac, but in my case, the problem was that I did not run the database (sudo mongod) before; the problem was solved when I first ran the mondo sudod on the console and, once it was done, on another console, the connection to the server ...

Zoe
  • 27,060
  • 21
  • 118
  • 148
0

i ran the local mysql database, but not in administrator mode, which threw this error

Timar Ivo Batis
  • 1,861
  • 17
  • 21
0

If you have stopped the mongod.exe service from the task manager, you need to restart the service. In my case I stopped the service from task manager and on restart it doesn't automatically started.

0

I got this error because my AdonisJS server was not running before I ran the test. Running the server first fixed it.

Daydah
  • 372
  • 7
  • 20
-1

Just run the following command in the node project:

npm install

Its worked for me.

Sunderam Dubey
  • 1
  • 11
  • 20
  • 40
manikandan
  • 677
  • 2
  • 8
  • 19
-1

I had the same issue on postman ,when try to connect docker container ,just double check the port your server is running and the endpoint (port you are tring to access),I changed the port it worked for me

Shiwantha Viraj
  • 301
  • 3
  • 8
-6

use a proxy property in your code it should work just fine

const https = require('https');
const request = require('request');

request({
    'url':'https://teamtreehouse.com/chalkers.json',
    'proxy':'http://xx.xxx.xxx.xx'
    },
    function (error, response, body) {
        if (!error && response.statusCode == 200) {
            var data = body;
            console.log(data);
        }
    }
);