Http error econnrefused

I am new to node and running into this error on a simple tutorial. I am on the OS X 10.8.2 trying this from CodeRunner and the Terminal. I have also tried putting my module in the node_modules fol...

I am new to node and running into this error on a simple tutorial.

I am on the OS X 10.8.2 trying this from CodeRunner and the Terminal.
I have also tried putting my module in the node_modules folder.

I can tell this is some kind of connection problem but I have no idea why?

events.js:71
        throw arguments[1]; // Unhandled 'error' event
                       ^
Error: connect ECONNREFUSED
    at errnoException (net.js:770:11)
    at Object.afterConnect [as oncomplete] (net.js:761:19)

app.js:

var makeRequest = require('./make_request');

makeRequest("Here's looking at you, kid");
makeRequest("Hello, this is dog");

make_request.js:

var http = require('http');

var makeRequest = function(message) {

    //var message = "Here's looking at you, kid.";
    var options = {
        host: 'localhost', port: 8080, path:'/', method: 'POST'
    }

    var request = http.request(options, function(response) {
        response.on('data', function(data) {
            console.log(data);
        });
    });
    request.write(message);
    request.end();
};

module.exports = makeRequest;

asked Jan 5, 2013 at 3:59

ian's user avatar

5

Chances are you are struggling with the node.js dying whenever the server you are calling refuses to connect. Try this:

process.on('uncaughtException', function (err) {
    console.log(err);
}); 

This keeps your server running and also give you a place to attach the debugger and look for a deeper problem.

answered Nov 5, 2013 at 16:23

user2957009's user avatar

user2957009user2957009

8326 silver badges10 bronze badges

3

You’re trying to connect to localhost:8080 … is any service running on your localhost and on this port? If not, the connection is refused which cause this error. I would suggest to check if there is anything running on localhost:8080 first.

answered Mar 23, 2013 at 11:38

JakubKnejzlik's user avatar

JakubKnejzlikJakubKnejzlik

6,2333 gold badges38 silver badges40 bronze badges

I was having the same issue with ghost and heroku.

heroku config:set NODE_ENV=production 

solved it!

Check your config and env that the server is running on.

Dan's user avatar

Dan

5,1154 gold badges31 silver badges42 bronze badges

answered Feb 23, 2014 at 5:09

Siddhartha Mukherjee's user avatar

2

If you are on MEAN (Mongo-Express-AngularJS-Node) stack, run mongod first, and this error message will go away.

answered May 17, 2016 at 14:29

Bob Vargas's user avatar

Bob VargasBob Vargas

1312 silver badges6 bronze badges

1

You need to have a server running on port 8080 when you run the code above that simply returns the request back through the response. Copy the code below to a separate file (say ‘server.js’) and start this server using the node command (node server.js). You can then separately run your code above (node app.js) from a separate command line.

var http = require('http');

http.createServer(function(request, response){

    //The following code will print out the incoming request text
    request.pipe(response);

}).listen(8080, '127.0.0.1');

console.log('Listening on port 8080...');

answered Jan 16, 2016 at 21:45

Andrew M.'s user avatar

Andrew M.Andrew M.

811 silver badge7 bronze badges

Sometimes it may occur, if there is any database connection in your code but you did not start the database server yet.

Im my case i have some piece of code to connect with mongodb

mongoose.connect("mongodb://localhost:27017/demoDb");

after i started the mongodb server with the command mongod this error is gone

answered Feb 26, 2016 at 19:22

pashaplus's user avatar

pashapluspashaplus

3,4482 gold badges25 silver badges24 bronze badges

ECONNREFUSED error means that connection could not be made with the target service (in your case localhost:8080). Check your service running on port 8080.

To know more about node.js errors, refer this doc.

answered Jul 26, 2021 at 12:45

Yuvaraj Anbarasan's user avatar

I just had this problem happen to me and after some searching for an answer I have found this other stackoverflow thread: ECONNREFUSED error with node.js that does not occur in other clients

The solution provided there, worked for me like a charm, it seems nodeJS has some issues accessing localhost dns, however switching to 127.0.0.1 works perfectly fine.

answered Jun 27, 2022 at 19:05

Vladimir Lazar's user avatar

2

People run into this error when the Node.js process is still running and they are attempting to start the server again. Try this:

ps aux | grep node

This will print something along the lines of:

user    7668  4.3  1.0  42060 10708 pts/1    Sl+  20:36   0:00 node server
user    7749  0.0  0.0   4384   832 pts/8    S+   20:37   0:00 grep --color=auto node

In this case, the process will be the one with the pid 7668. To kill it and restart the server, run kill -9 7668.

answered Jan 5, 2013 at 4:38

rahulmehta95's user avatar

1

Check with starting mysql in terminal. Use below command

mysql-ctl start

In my case its worked

answered Jun 25, 2015 at 12:36

mujaffars's user avatar

mujaffarsmujaffars

1,3852 gold badges14 silver badges35 bronze badges

Run server.js from a different command line and client.js from a different command line

answered Jun 11, 2019 at 5:50

shamila's user avatar

shamilashamila

1,2206 gold badges20 silver badges45 bronze badges

For me it was a problem in library node-agent-base v4.x which was requested by https-proxy-agent which in it’s side was requested by newrelic v5.x library.

The problem was that node-agent-base v4.x for some marvellous idea decided to patch core https.get request (You can see this in the file patch-core.js in the repo). And when I used library which use https.get, it was failed because node-agent-base v4.x have changed function signature, which gave me request to 127.0.0.1 as initial url was lost…

I’ve fixed this by updating to the next version of newrelic 6.x, where node-agent-base v4.x doesn’t has such ‘patches’.

This is just crazy…hope my response will save you some time, I’ve spent several days to debug this.

answered Jan 31, 2022 at 11:15

KorbenDallas's user avatar

The Unhandled 'error' event is referring not providing a function to the request to pass errors. Without this event the node process ends with the error instead of failing gracefully and providing actual feedback. You can set the event just before the request.write line to catch any issues:

request.on('error', function(err)
{
    console.log(err);
});

More examples below:

https://nodejs.org/api/http.html#http_http_request_options_callback

answered Mar 17, 2016 at 22:25

SmujMaiku's user avatar

SmujMaikuSmujMaiku

5615 silver badges10 bronze badges

Had a similar issue, it turned out the listening port printed was different from what it actually was. Typos in the request string or listening function might make the target server appear to not exist.

answered Oct 14, 2020 at 16:26

Ricardo Mitchell's user avatar

In my case I forget to npm start the node app

answered Sep 11, 2022 at 22:01

Muhammad Javed Baloch's user avatar

If you are using NodeJs version > 17, try to downgrade to use NodeJs 16.
On 17, by default, the debugger bind IP is on IPv6, and sometimes you IDE might not be able to attach to it

answered Sep 15, 2022 at 13:36

Steven Shi's user avatar

Steven ShiSteven Shi

9121 gold badge8 silver badges10 bronze badges

For me this happened when my .env file was named incorrectly to .env.local

answered Nov 30, 2022 at 19:26

Alistair St Pierre's user avatar

1

I was having the same issue in my dev env with Postman when checking the API.
I searched literally all the answers came from google, but no avail.

SOLUTION:
I have just moved to «insomnia» (an alternative to Postman) and it works just fine. Hope this workaround may help.

answered Nov 24, 2021 at 13:48

E. Djalalov's user avatar

I am new to node and running into this error on a simple tutorial.

I am on the OS X 10.8.2 trying this from CodeRunner and the Terminal.
I have also tried putting my module in the node_modules folder.

I can tell this is some kind of connection problem but I have no idea why?

events.js:71
        throw arguments[1]; // Unhandled 'error' event
                       ^
Error: connect ECONNREFUSED
    at errnoException (net.js:770:11)
    at Object.afterConnect [as oncomplete] (net.js:761:19)

app.js:

var makeRequest = require('./make_request');

makeRequest("Here's looking at you, kid");
makeRequest("Hello, this is dog");

make_request.js:

var http = require('http');

var makeRequest = function(message) {

    //var message = "Here's looking at you, kid.";
    var options = {
        host: 'localhost', port: 8080, path:'/', method: 'POST'
    }

    var request = http.request(options, function(response) {
        response.on('data', function(data) {
            console.log(data);
        });
    });
    request.write(message);
    request.end();
};

module.exports = makeRequest;

asked Jan 5, 2013 at 3:59

ian's user avatar

5

Chances are you are struggling with the node.js dying whenever the server you are calling refuses to connect. Try this:

process.on('uncaughtException', function (err) {
    console.log(err);
}); 

This keeps your server running and also give you a place to attach the debugger and look for a deeper problem.

answered Nov 5, 2013 at 16:23

user2957009's user avatar

user2957009user2957009

8326 silver badges10 bronze badges

3

You’re trying to connect to localhost:8080 … is any service running on your localhost and on this port? If not, the connection is refused which cause this error. I would suggest to check if there is anything running on localhost:8080 first.

answered Mar 23, 2013 at 11:38

JakubKnejzlik's user avatar

JakubKnejzlikJakubKnejzlik

6,2333 gold badges38 silver badges40 bronze badges

I was having the same issue with ghost and heroku.

heroku config:set NODE_ENV=production 

solved it!

Check your config and env that the server is running on.

Dan's user avatar

Dan

5,1154 gold badges31 silver badges42 bronze badges

answered Feb 23, 2014 at 5:09

Siddhartha Mukherjee's user avatar

2

If you are on MEAN (Mongo-Express-AngularJS-Node) stack, run mongod first, and this error message will go away.

answered May 17, 2016 at 14:29

Bob Vargas's user avatar

Bob VargasBob Vargas

1312 silver badges6 bronze badges

1

You need to have a server running on port 8080 when you run the code above that simply returns the request back through the response. Copy the code below to a separate file (say ‘server.js’) and start this server using the node command (node server.js). You can then separately run your code above (node app.js) from a separate command line.

var http = require('http');

http.createServer(function(request, response){

    //The following code will print out the incoming request text
    request.pipe(response);

}).listen(8080, '127.0.0.1');

console.log('Listening on port 8080...');

answered Jan 16, 2016 at 21:45

Andrew M.'s user avatar

Andrew M.Andrew M.

811 silver badge7 bronze badges

Sometimes it may occur, if there is any database connection in your code but you did not start the database server yet.

Im my case i have some piece of code to connect with mongodb

mongoose.connect("mongodb://localhost:27017/demoDb");

after i started the mongodb server with the command mongod this error is gone

answered Feb 26, 2016 at 19:22

pashaplus's user avatar

pashapluspashaplus

3,4482 gold badges25 silver badges24 bronze badges

ECONNREFUSED error means that connection could not be made with the target service (in your case localhost:8080). Check your service running on port 8080.

To know more about node.js errors, refer this doc.

answered Jul 26, 2021 at 12:45

Yuvaraj Anbarasan's user avatar

I just had this problem happen to me and after some searching for an answer I have found this other stackoverflow thread: ECONNREFUSED error with node.js that does not occur in other clients

The solution provided there, worked for me like a charm, it seems nodeJS has some issues accessing localhost dns, however switching to 127.0.0.1 works perfectly fine.

answered Jun 27, 2022 at 19:05

Vladimir Lazar's user avatar

2

People run into this error when the Node.js process is still running and they are attempting to start the server again. Try this:

ps aux | grep node

This will print something along the lines of:

user    7668  4.3  1.0  42060 10708 pts/1    Sl+  20:36   0:00 node server
user    7749  0.0  0.0   4384   832 pts/8    S+   20:37   0:00 grep --color=auto node

In this case, the process will be the one with the pid 7668. To kill it and restart the server, run kill -9 7668.

answered Jan 5, 2013 at 4:38

rahulmehta95's user avatar

1

Check with starting mysql in terminal. Use below command

mysql-ctl start

In my case its worked

answered Jun 25, 2015 at 12:36

mujaffars's user avatar

mujaffarsmujaffars

1,3852 gold badges14 silver badges35 bronze badges

Run server.js from a different command line and client.js from a different command line

answered Jun 11, 2019 at 5:50

shamila's user avatar

shamilashamila

1,2206 gold badges20 silver badges45 bronze badges

For me it was a problem in library node-agent-base v4.x which was requested by https-proxy-agent which in it’s side was requested by newrelic v5.x library.

The problem was that node-agent-base v4.x for some marvellous idea decided to patch core https.get request (You can see this in the file patch-core.js in the repo). And when I used library which use https.get, it was failed because node-agent-base v4.x have changed function signature, which gave me request to 127.0.0.1 as initial url was lost…

I’ve fixed this by updating to the next version of newrelic 6.x, where node-agent-base v4.x doesn’t has such ‘patches’.

This is just crazy…hope my response will save you some time, I’ve spent several days to debug this.

answered Jan 31, 2022 at 11:15

KorbenDallas's user avatar

The Unhandled 'error' event is referring not providing a function to the request to pass errors. Without this event the node process ends with the error instead of failing gracefully and providing actual feedback. You can set the event just before the request.write line to catch any issues:

request.on('error', function(err)
{
    console.log(err);
});

More examples below:

https://nodejs.org/api/http.html#http_http_request_options_callback

answered Mar 17, 2016 at 22:25

SmujMaiku's user avatar

SmujMaikuSmujMaiku

5615 silver badges10 bronze badges

Had a similar issue, it turned out the listening port printed was different from what it actually was. Typos in the request string or listening function might make the target server appear to not exist.

answered Oct 14, 2020 at 16:26

Ricardo Mitchell's user avatar

In my case I forget to npm start the node app

answered Sep 11, 2022 at 22:01

Muhammad Javed Baloch's user avatar

If you are using NodeJs version > 17, try to downgrade to use NodeJs 16.
On 17, by default, the debugger bind IP is on IPv6, and sometimes you IDE might not be able to attach to it

answered Sep 15, 2022 at 13:36

Steven Shi's user avatar

Steven ShiSteven Shi

9121 gold badge8 silver badges10 bronze badges

For me this happened when my .env file was named incorrectly to .env.local

answered Nov 30, 2022 at 19:26

Alistair St Pierre's user avatar

1

I was having the same issue in my dev env with Postman when checking the API.
I searched literally all the answers came from google, but no avail.

SOLUTION:
I have just moved to «insomnia» (an alternative to Postman) and it works just fine. Hope this workaround may help.

answered Nov 24, 2021 at 13:48

E. Djalalov's user avatar

You will encounter various kinds of errors while developing Node.js
applications, but most can be avoided or easily mitigated with the right coding
practices. However, most of the information to fix these problems are currently
scattered across various GitHub issues and forum posts which could lead to
spending more time than necessary when seeking solutions.

Therefore, we’ve compiled this list of 15 common Node.js errors along with one
or more strategies to follow to fix each one. While this is not a comprehensive
list of all the errors you can encounter when developing Node.js applications,
it should help you understand why some of these common errors occur and feasible
solutions to avoid future recurrence.

🔭 Want to centralize and monitor your Node.js error logs?

Head over to Logtail and start ingesting your logs in 5 minutes.

1. ECONNRESET

ECONNRESET is a common exception that occurs when the TCP connection to
another server is closed abruptly, usually before a response is received. It can
be emitted when you attempt a request through a TCP connection that has already
been closed or when the connection is closed before a response is received
(perhaps in case of a timeout). This exception will usually
look like the following depending on your version of Node.js:

Output

Error: socket hang up
    at connResetException (node:internal/errors:691:14)
    at Socket.socketOnEnd (node:_http_client:466:23)
    at Socket.emit (node:events:532:35)
    at endReadableNT (node:internal/streams/readable:1346:12)
    at processTicksAndRejections (node:internal/process/task_queues:83:21) {
  code: 'ECONNRESET'
}

If this exception occurs when making a request to another server, you should
catch it and decide how to handle it. For example, you can retry the request
immediately, or queue it for later. You can also investigate your timeout
settings if you’d like to wait longer for the request to be
completed.

On the other hand, if it is caused by a client deliberately closing an
unfulfilled request to your server, then you don’t need to do anything except
end the connection (res.end()), and stop any operations performed in
generating a response. You can detect if a client socket was destroyed through
the following:

app.get("/", (req, res) => {
  // listen for the 'close' event on the request
  req.on("close", () => {
    console.log("closed connection");
  });

  console.log(res.socket.destroyed); // true if socket is closed
});

2. ENOTFOUND

The ENOTFOUND exception occurs in Node.js when a connection cannot be
established to some host due to a DNS error. This usually occurs due to an
incorrect host value, or when localhost is not mapped correctly to
127.0.0.1. It can also occur when a domain goes down or no longer exists.
Here’s an example of how the error often appears in the Node.js console:

Output

Error: getaddrinfo ENOTFOUND http://localhost
    at GetAddrInfoReqWrap.onlookup [as oncomplete] (node:dns:71:26) {
  errno: -3008,
  code: 'ENOTFOUND',
  syscall: 'getaddrinfo',
  hostname: 'http://localhost'
}

If you get this error in your Node.js application or while running a script, you
can try the following strategies to fix it:

Check the domain name

First, ensure that you didn’t make a typo while entering the domain name. You
can also use a tool like DNS Checker to confirm that
the domain is resolving successfully in your location or region.

Check the host value

If you’re using http.request() or https.request() methods from the standard
library, ensure that the host value in the options object contains only the
domain name or IP address of the server. It shouldn’t contain the protocol,
port, or request path (use the protocol, port, and path properties for
those values respectively).

// don't do this
const options = {
  host: 'http://example.com/path/to/resource',
};

// do this instead
const options = {
  host: 'example.com',
  path: '/path/to/resource',
};

http.request(options, (res) => {});

Check your localhost mapping

If you’re trying to connect to localhost, and the ENOTFOUND error is thrown,
it may mean that the localhost is missing in your hosts file. On Linux and
macOS, ensure that your /etc/hosts file contains the following entry:

You may need to flush your DNS cache afterward:

sudo killall -HUP mDNSResponder # macOS

On Linux, clearing the DNS cache depends on the distribution and caching service
in use. Therefore, do investigate the appropriate command to run on your system.

3. ETIMEDOUT

The ETIMEDOUT error is thrown by the Node.js runtime when a connection or HTTP
request is not closed properly after some time. You might encounter this error
from time to time if you configured a timeout on your
outgoing HTTP requests. The general solution to this issue is to catch the error
and repeat the request, preferably using an
exponential backoff
strategy so that a waiting period is added between subsequent retries until the
request eventually succeeds, or the maximum amount of retries is reached. If you
encounter this error frequently, try to investigate your request timeout
settings and choose a more appropriate value for the endpoint
if possible.

4. ECONNREFUSED

The ECONNREFUSED error is produced when a request is made to an endpoint but a
connection could not be established because the specified address wasn’t
reachable. This is usually caused by an inactive target service. For example,
the error below resulted from attempting to connect to http://localhost:8000
when no program is listening at that endpoint.

Error: connect ECONNREFUSED 127.0.0.1:8000
    at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1157:16)
Emitted 'error' event on ClientRequest instance at:
    at Socket.socketErrorListener (node:_http_client:442:9)
    at Socket.emit (node:events:526:28)
    at emitErrorNT (node:internal/streams/destroy:157:8)
    at emitErrorCloseNT (node:internal/streams/destroy:122:3)
    at processTicksAndRejections (node:internal/process/task_queues:83:21) {
  errno: -111,
  code: 'ECONNREFUSED',
  syscall: 'connect',
  address: '127.0.0.1',
  port: 8000
}

The fix for this problem is to ensure that the target service is active and
accepting connections at the specified endpoint.

5. ERRADDRINUSE

This error is commonly encountered when starting or restarting a web server. It
indicates that the server is attempting to listen for connections at a port that
is already occupied by some other application.

Error: listen EADDRINUSE: address already in use :::3001
    at Server.setupListenHandle [as _listen2] (node:net:1330:16)
    at listenInCluster (node:net:1378:12)
    at Server.listen (node:net:1465:7)
    at Function.listen (/home/ayo/dev/demo/node_modules/express/lib/application.js:618:24)
    at Object.<anonymous> (/home/ayo/dev/demo/main.js:16:18)
    at Module._compile (node:internal/modules/cjs/loader:1103:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1157:10)
    at Module.load (node:internal/modules/cjs/loader:981:32)
    at Function.Module._load (node:internal/modules/cjs/loader:822:12)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:77:12)
Emitted 'error' event on Server instance at:
    at emitErrorNT (node:net:1357:8)
    at processTicksAndRejections (node:internal/process/task_queues:83:21) {
  code: 'EADDRINUSE',
  errno: -98,
  syscall: 'listen',
  address: '::',
  port: 3001
}

The easiest fix for this error would be to configure your application to listen
on a different port (preferably by updating an environmental variable). However,
if you need that specific port that is in use, you can find out the process ID
of the application using it through the command below:

Output

COMMAND  PID USER   FD   TYPE DEVICE SIZE/OFF NODE NAME
node    2902  ayo   19u  IPv6 781904      0t0  TCP *:3001 (LISTEN)

Afterward, kill the process by passing the PID value to the kill command:

After running the command above, the application will be forcefully closed
freeing up the desired port for your intended use.

6. EADDRNOTAVAIL

This error is similar to EADDRINUSE because it results from trying to run a
Node.js server at a specific port. It usually indicates a configuration issue
with your IP address, such as when you try to bind your server to a static IP:

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

const server = app.listen(3000, '192.168.0.101', function () {
  console.log('server listening at port 3000......');
});

Output

Error: listen EADDRNOTAVAIL: address not available 192.168.0.101:3000
    at Server.setupListenHandle [as _listen2] (node:net:1313:21)
    at listenInCluster (node:net:1378:12)
    at doListen (node:net:1516:7)
    at processTicksAndRejections (node:internal/process/task_queues:84:21)
Emitted 'error' event on Server instance at:
    at emitErrorNT (node:net:1357:8)
    at processTicksAndRejections (node:internal/process/task_queues:83:21) {
  code: 'EADDRNOTAVAIL',
  errno: -99,
  syscall: 'listen',
  address: '192.168.0.101',
  port: 3000
}

To resolve this issue, ensure that you have the right IP address (it may
sometimes change), or you can bind to any or all IPs by using 0.0.0.0 as shown
below:

var server = app.listen(3000, '0.0.0.0', function () {
  console.log('server listening at port 3000......');
});

7. ECONNABORTED

The ECONNABORTED exception is thrown when an active network connection is
aborted by the server before reading from the request body or writing to the
response body has completed. The example below demonstrates how this problem can
occur in a Node.js program:

const express = require('express');
const app = express();
const path = require('path');

app.get('/', function (req, res, next) {
  res.sendFile(path.join(__dirname, 'new.txt'), null, (err) => {
    console.log(err);
  });
  res.end();
});

const server = app.listen(3000, () => {
  console.log('server listening at port 3001......');
});

Output

Error: Request aborted
    at onaborted (/home/ayo/dev/demo/node_modules/express/lib/response.js:1030:15)
    at Immediate._onImmediate (/home/ayo/dev/demo/node_modules/express/lib/response.js:1072:9)
    at processImmediate (node:internal/timers:466:21) {
  code: 'ECONNABORTED'
}

The problem here is that res.end() was called prematurely before
res.sendFile() has had a chance to complete due to the asynchronous nature of
the method. The solution here is to move res.end() into sendFile()‘s
callback function:

app.get('/', function (req, res, next) {
  res.sendFile(path.join(__dirname, 'new.txt'), null, (err) => {
    console.log(err);
    res.end();
  });
});

8. EHOSTUNREACH

An EHOSTUNREACH exception indicates that a TCP connection failed because the
underlying protocol software found no route to the network or host. It can also
be triggered when traffic is blocked by a firewall or in response to information
received by intermediate gateways or switching nodes. If you encounter this
error, you may need to check your operating system’s routing tables or firewall
setup to fix the problem.

9. EAI_AGAIN

Node.js throws an EAI_AGAIN error when a temporary failure in domain name
resolution occurs. A DNS lookup timeout that usually indicates a problem with
your network connection or your proxy settings. You can get this error when
trying to install an npm package:

Output

npm ERR! code EAI_AGAIN
npm ERR! syscall getaddrinfo
npm ERR! errno EAI_AGAIN
npm ERR! request to https://registry.npmjs.org/nestjs failed, reason: getaddrinfo EAI_AGAIN registry.npmjs.org

If you’ve determined that your internet connection is working correctly, then
you should investigate your DNS resolver settings (/etc/resolv.conf) or your
/etc/hosts file to ensure it is set up correctly.

10. ENOENT

This error is a straightforward one. It means «Error No Entity» and is raised
when a specified path (file or directory) does not exist in the filesystem. It
is most commonly encountered when performing an operation with the fs module
or running a script that expects a specific directory structure.

fs.open('non-existent-file.txt', (err, fd) => {
  if (err) {
    console.log(err);
  }
});

Output

[Error: ENOENT: no such file or directory, open 'non-existent-file.txt'] {
  errno: -2,
  code: 'ENOENT',
  syscall: 'open',
  path: 'non-existent-file.txt'
}

To fix this error, you either need to create the expected directory structure or
change the path so that the script looks in the correct directory.

11. EISDIR

If you encounter this error, the operation that raised it expected a file
argument but was provided with a directory.

// config is actually a directory
fs.readFile('config', (err, data) => {
  if (err) throw err;
  console.log(data);
});

Output

[Error: EISDIR: illegal operation on a directory, read] {
  errno: -21,
  code: 'EISDIR',
  syscall: 'read'
}

Fixing this error involves correcting the provided path so that it leads to a
file instead.

12. ENOTDIR

This error is the inverse of EISDIR. It means a file argument was supplied
where a directory was expected. To avoid this error, ensure that the provided
path leads to a directory and not a file.

fs.opendir('/etc/passwd', (err, _dir) => {
  if (err) throw err;
});

Output

[Error: ENOTDIR: not a directory, opendir '/etc/passwd'] {
  errno: -20,
  code: 'ENOTDIR',
  syscall: 'opendir',
  path: '/etc/passwd'
}

13. EACCES

The EACCES error is often encountered when trying to access a file in a way
that is forbidden by its access permissions. You may also encounter this error
when you’re trying to install a global NPM package (depending on how you
installed Node.js and npm), or when you try to run a server on a port lower
than 1024.

fs.readFile('/etc/sudoers', (err, data) => {
  if (err) throw err;
  console.log(data);
});

Output

[Error: EACCES: permission denied, open '/etc/sudoers'] {
  errno: -13,
  code: 'EACCES',
  syscall: 'open',
  path: '/etc/sudoers'
}

Essentially, this error indicates that the user executing the script does not
have the required permission to access a resource. A quick fix is to prefix the
script execution command with sudo so that it is executed as root, but this is
a bad idea
for security reasons.

The correct fix for this error is to give the user executing the script the
required permissions to access the resource through the chown command on Linux
in the case of a file or directory.

sudo chown -R $(whoami) /path/to/directory

If you encounter an EACCES error when trying to listen on a port lower than
1024, you can use a higher port and set up port forwarding through iptables.
The following command forwards HTTP traffic going to port 80 to port 8080
(assuming your application is listening on port 8080):

sudo iptables -t nat -I PREROUTING -p tcp --dport 80 -j REDIRECT --to-port 8080

If you encounter EACCES errors when trying to install a global npm package,
it usually means that you installed the Node.js and npm versions found in your
system’s repositories. The recommended course of action is to uninstall those
versions and reinstall them through a Node environment manager like
NVM or Volta.

14. EEXIST

The EEXIST error is another filesystem error that is encountered whenever a
file or directory exists, but the attempted operation requires it not to exist.
For example, you will see this error when you attempt to create a directory that
already exists as shown below:

const fs = require('fs');

fs.mkdirSync('temp', (err) => {
  if (err) throw err;
});

Output

Error: EEXIST: file already exists, mkdir 'temp'
    at Object.mkdirSync (node:fs:1349:3)
    at Object.<anonymous> (/home/ayo/dev/demo/main.js:3:4)
    at Module._compile (node:internal/modules/cjs/loader:1099:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
    at Module.load (node:internal/modules/cjs/loader:975:32)
    at Function.Module._load (node:internal/modules/cjs/loader:822:12)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:77:12)
    at node:internal/main/run_main_module:17:47 {
  errno: -17,
  syscall: 'mkdir',
  code: 'EEXIST',
  path: 'temp'
}

The solution here is to check if the path exists through fs.existsSync()
before attempting to create it:

const fs = require('fs');

if (!fs.existsSync('temp')) {
  fs.mkdirSync('temp', (err) => {
    if (err) throw err;
  });
}

15. EPERM

The EPERM error may be encountered in various scenarios, usually when
installing an npm package. It indicates that the operation being carried out
could not be completed due to permission issues. This error often indicates that
a write was attempted to a file that is in a read-only state although you may
sometimes encounter an EACCES error instead.

Here are some possible fixes you can try if you run into this problem:

  1. Close all instances of your editor before rerunning the command (maybe some
    files were locked by the editor).
  2. Clean the npm cache with npm cache clean --force.
  3. Close or disable your Anti-virus software if have one.
  4. If you have a development server running, stop it before executing the
    installation command once again.
  5. Use the --force option as in npm install --force.
  6. Remove your node_modules folder with rm -rf node_modules and install them
    once again with npm install.

Conclusion

In this article, we covered 15 of the most common Node.js errors you are likely
to encounter when developing applications or utilizing Node.js-based tools, and
we discussed possible solutions to each one. This by no means an exhaustive list
so ensure to check out the
Node.js errors documentation or the
errno(3) man page for a
more comprehensive listing.

Thanks for reading, and happy coding!

Check Uptime, Ping, Ports, SSL and more.

Get Slack, SMS and phone incident alerts.

Easy on-call duty scheduling.

Create free status page on your domain.

Got an article suggestion?
Let us know

Share on Twitter

Share on Facebook

Share via e-mail

Next article

How to Configure Nginx as a Reverse Proxy for Node.js Applications

Licensed under CC-BY-NC-SA

This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.

Содержание

  1. ConnectionRefusedError: [Errno 111] ECONNREFUSED #201
  2. Comments
  3. 15 Common Error Codes in Node.js and How to Fix Them
  4. 🔭 Want to centralize and monitor your Node.js error logs?
  5. 1. ECONNRESET
  6. 2. ENOTFOUND
  7. Check the domain name
  8. Check the host value
  9. Check your localhost mapping
  10. 3. ETIMEDOUT
  11. 4. ECONNREFUSED
  12. 5. ERRADDRINUSE
  13. 6. EADDRNOTAVAIL
  14. 7. ECONNABORTED
  15. 8. EHOSTUNREACH
  16. 9. EAI_AGAIN
  17. 10. ENOENT
  18. 11. EISDIR
  19. 12. ENOTDIR
  20. 13. EACCES
  21. 14. EEXIST
  22. 15. EPERM
  23. ConnectionRefusedError: [Errno 111] Connection Refused
  24. Why the ConnectionRefusedError: [Errno 111] Connection refused Occurs in Python
  25. How to Solve the ConnectionRefusedError: [Errno 111] Connection refused in Python
  26. Use gethostbyname
  27. Conclusion

ConnectionRefusedError: [Errno 111] ECONNREFUSED #201

Hello! I am new to Docker, but have had serious issues connecting to a redis database from within a container. This is the error I am getting:

my server.py file is a flask application ran as Flask Socket IO.

When i do docker-compose ps i get this:

Does anyone have any ideas? Nothing online has been working for me. Thank you.

The text was updated successfully, but these errors were encountered:

Is your python container trying to connect to localhost:6379?
The redis container looks like it’s behaving just fine

Connecting to redis from another container:

@wglambert it appears like the python container is trying to connect to localhost:6379 as shown at the end of the error message

And is the aim of that to connect to the redis database?
Would that database be located in the python container or in the redis container; if it’s the latter then try swapping that to the name of the redis container.

So in my code, I changed my redis server to be.

Now, when I call docker-compose up, it hangs on the server, and never even runs the python script.

That’s not necessarily a «hang» but a «wait». As you’re attached to its log output without the -d option in docker compose up .
You can ctrl+z that (ctrl+c will stop your containers).

Since you’re only looking at log output here, it’s possible your script ran without outputting anything. Doing docker exec testchatservercopy_web_1 ps will probably show your script as PID 1. And it hasn’t exited after establishing a connection so it’s just waiting and keeping the container running.

If you have further questions you should try asking the Docker Community Forums, Docker Community Slack, or Stack Overflow. Since these repositories are for issues with the image and not necessarily for questions of usability

Источник

15 Common Error Codes in Node.js and How to Fix Them

Contents

You will encounter various kinds of errors while developing Node.js applications, but most can be avoided or easily mitigated with the right coding practices. However, most of the information to fix these problems are currently scattered across various GitHub issues and forum posts which could lead to spending more time than necessary when seeking solutions.

Therefore, we’ve compiled this list of 15 common Node.js errors along with one or more strategies to follow to fix each one. While this is not a comprehensive list of all the errors you can encounter when developing Node.js applications, it should help you understand why some of these common errors occur and feasible solutions to avoid future recurrence.

lightbox#close» data-lightbox-target=»img» src=»https://imagedelivery.net/xZXo0QFi-1_4Zimer-T0XQ/ac93c9ef-a7f6-4cff-0bcd-14982ccc7f00/orig»/>

🔭 Want to centralize and monitor your Node.js error logs?

Head over to Logtail and start ingesting your logs in 5 minutes.

1. ECONNRESET

ECONNRESET is a common exception that occurs when the TCP connection to another server is closed abruptly, usually before a response is received. It can be emitted when you attempt a request through a TCP connection that has already been closed or when the connection is closed before a response is received (perhaps in case of a timeout). This exception will usually look like the following depending on your version of Node.js:

If this exception occurs when making a request to another server, you should catch it and decide how to handle it. For example, you can retry the request immediately, or queue it for later. You can also investigate your timeout settings if you’d like to wait longer for the request to be completed.

On the other hand, if it is caused by a client deliberately closing an unfulfilled request to your server, then you don’t need to do anything except end the connection ( res.end() ), and stop any operations performed in generating a response. You can detect if a client socket was destroyed through the following:

2. ENOTFOUND

The ENOTFOUND exception occurs in Node.js when a connection cannot be established to some host due to a DNS error. This usually occurs due to an incorrect host value, or when localhost is not mapped correctly to 127.0.0.1 . It can also occur when a domain goes down or no longer exists. Here’s an example of how the error often appears in the Node.js console:

If you get this error in your Node.js application or while running a script, you can try the following strategies to fix it:

Check the domain name

First, ensure that you didn’t make a typo while entering the domain name. You can also use a tool like DNS Checker

to confirm that the domain is resolving successfully in your location or region.

Check the host value

If you’re using http.request() or https.request() methods from the standard library, ensure that the host value in the options object contains only the domain name or IP address of the server. It shouldn’t contain the protocol, port, or request path (use the protocol , port , and path properties for those values respectively).

Check your localhost mapping

If you’re trying to connect to localhost , and the ENOTFOUND error is thrown, it may mean that the localhost is missing in your hosts file. On Linux and macOS, ensure that your /etc/hosts file contains the following entry:

You may need to flush your DNS cache afterward:

On Linux, clearing the DNS cache depends on the distribution and caching service in use. Therefore, do investigate the appropriate command to run on your system.

3. ETIMEDOUT

The ETIMEDOUT error is thrown by the Node.js runtime when a connection or HTTP request is not closed properly after some time. You might encounter this error from time to time if you configured a timeout on your outgoing HTTP requests. The general solution to this issue is to catch the error and repeat the request, preferably using an exponential backoff

strategy so that a waiting period is added between subsequent retries until the request eventually succeeds, or the maximum amount of retries is reached. If you encounter this error frequently, try to investigate your request timeout settings and choose a more appropriate value for the endpoint if possible.

4. ECONNREFUSED

The ECONNREFUSED error is produced when a request is made to an endpoint but a connection could not be established because the specified address wasn’t reachable. This is usually caused by an inactive target service. For example, the error below resulted from attempting to connect to http://localhost:8000 when no program is listening at that endpoint.

The fix for this problem is to ensure that the target service is active and accepting connections at the specified endpoint.

5. ERRADDRINUSE

This error is commonly encountered when starting or restarting a web server. It indicates that the server is attempting to listen for connections at a port that is already occupied by some other application.

The easiest fix for this error would be to configure your application to listen on a different port (preferably by updating an environmental variable). However, if you need that specific port that is in use, you can find out the process ID of the application using it through the command below:

Afterward, kill the process by passing the PID value to the kill command:

After running the command above, the application will be forcefully closed freeing up the desired port for your intended use.

6. EADDRNOTAVAIL

This error is similar to EADDRINUSE because it results from trying to run a Node.js server at a specific port. It usually indicates a configuration issue with your IP address, such as when you try to bind your server to a static IP:

To resolve this issue, ensure that you have the right IP address (it may sometimes change), or you can bind to any or all IPs by using 0.0.0.0 as shown below:

7. ECONNABORTED

The ECONNABORTED exception is thrown when an active network connection is aborted by the server before reading from the request body or writing to the response body has completed. The example below demonstrates how this problem can occur in a Node.js program:

The problem here is that res.end() was called prematurely before res.sendFile() has had a chance to complete due to the asynchronous nature of the method. The solution here is to move res.end() into sendFile() ‘s callback function:

8. EHOSTUNREACH

An EHOSTUNREACH exception indicates that a TCP connection failed because the underlying protocol software found no route to the network or host. It can also be triggered when traffic is blocked by a firewall or in response to information received by intermediate gateways or switching nodes. If you encounter this error, you may need to check your operating system’s routing tables or firewall setup to fix the problem.

9. EAI_AGAIN

Node.js throws an EAI_AGAIN error when a temporary failure in domain name resolution occurs. A DNS lookup timeout that usually indicates a problem with your network connection or your proxy settings. You can get this error when trying to install an npm package:

If you’ve determined that your internet connection is working correctly, then you should investigate your DNS resolver settings ( /etc/resolv.conf ) or your /etc/hosts file to ensure it is set up correctly.

10. ENOENT

This error is a straightforward one. It means «Error No Entity» and is raised when a specified path (file or directory) does not exist in the filesystem. It is most commonly encountered when performing an operation with the fs module or running a script that expects a specific directory structure.

To fix this error, you either need to create the expected directory structure or change the path so that the script looks in the correct directory.

11. EISDIR

If you encounter this error, the operation that raised it expected a file argument but was provided with a directory.

Fixing this error involves correcting the provided path so that it leads to a file instead.

12. ENOTDIR

This error is the inverse of EISDIR . It means a file argument was supplied where a directory was expected. To avoid this error, ensure that the provided path leads to a directory and not a file.

13. EACCES

The EACCES error is often encountered when trying to access a file in a way that is forbidden by its access permissions. You may also encounter this error when you’re trying to install a global NPM package (depending on how you installed Node.js and npm ), or when you try to run a server on a port lower than 1024.

Essentially, this error indicates that the user executing the script does not have the required permission to access a resource. A quick fix is to prefix the script execution command with sudo so that it is executed as root, but this is a bad idea for security reasons

The correct fix for this error is to give the user executing the script the required permissions to access the resource through the chown command on Linux in the case of a file or directory.

If you encounter an EACCES error when trying to listen on a port lower than 1024, you can use a higher port and set up port forwarding through iptables . The following command forwards HTTP traffic going to port 80 to port 8080 (assuming your application is listening on port 8080):

If you encounter EACCES errors when trying to install a global npm package, it usually means that you installed the Node.js and npm versions found in your system’s repositories. The recommended course of action is to uninstall those versions and reinstall them through a Node environment manager like NVM

14. EEXIST

The EEXIST error is another filesystem error that is encountered whenever a file or directory exists, but the attempted operation requires it not to exist. For example, you will see this error when you attempt to create a directory that already exists as shown below:

The solution here is to check if the path exists through fs.existsSync() before attempting to create it:

15. EPERM

The EPERM error may be encountered in various scenarios, usually when installing an npm package. It indicates that the operation being carried out could not be completed due to permission issues. This error often indicates that a write was attempted to a file that is in a read-only state although you may sometimes encounter an EACCES error instead.

Here are some possible fixes you can try if you run into this problem:

  1. Close all instances of your editor before rerunning the command (maybe some files were locked by the editor).
  2. Clean the npm cache with npm cache clean —force .
  3. Close or disable your Anti-virus software if have one.
  4. If you have a development server running, stop it before executing the installation command once again.
  5. Use the —force option as in npm install —force .
  6. Remove your node_modules folder with rm -rf node_modules and install them once again with npm install .

Источник

ConnectionRefusedError: [Errno 111] Connection Refused

This error indicates that the client cannot connect to the port on the server script’s system. Since you can ping the server, it should not be the case.

This might be caused by many reasons, such as improper routing to the destination. The second possibility is that you have a firewall between your client and server, which may be either on the server or the client.

There shouldn’t be any routers or firewalls that may stop the communication since, based on your network addresses, both the server and the client should be on the same Local Area Network.

Why the ConnectionRefusedError: [Errno 111] Connection refused Occurs in Python

This error arises when the client cannot access the server because of an invalid IP or port or if the address is not unique and used by another server.

The connection refused error also arises when the server is not running, so the client cannot access the server as the server should accept the connection first.

How to Solve the ConnectionRefusedError: [Errno 111] Connection refused in Python

Try to keep the receiving socket as accessible as possible. Perhaps accessibility would only take place on one interface, which would not impact the Local Area Network.

On the other hand, one case can be that it exclusively listens to the address 127.0.0.1 , making connections from other hosts impossible.

When you run the command python server.py , you will receive the message Got connection . At the same time when you run the command python client.py , you will receive a message from the server.

The DNS resolution can be the other reason behind this problem. Since the socket.gethostname() returns the hostname, an error will be returned if the operating system cannot translate it to a local address.

The Linux operating system can edit the host file by adding one line.

Use gethostbyname

Thus, you must use the identical technique on the client and server sides to access the host. For instance, you would apply the procedure described above in a client’s case.

You can also access through local hostname hostnamehost = socket.gethostname() or specific name for local host host = socket.gethostbyname(«localhost») .

Conclusion

ConnectionRefusedError in Python arises when the client cannot connect to the server. Several reasons include the client not knowing the IP or port address and the server not running when the client wants to connect.

There are several methods mentioned above to resolve this connection issue.

Zeeshan is a detail oriented software engineer that helps companies and individuals make their lives and easier with software solutions.

Источник

Describe the bug

Axios returns ECONNREFUSED 127.0.0.1:80 but port is set to 8080

To Reproduce

While having an express server returning 200 on http://localhost:8080/ (and confirmed via browser), running the following returns the error provided (see additional context)

axios({
  headers: { Accept: 'text/html, application/json, text/plain, */*' },
  proxy: undefined,
  url: 'http://localhost:8080',
  method: 'get'
});

Expected behavior

Axios sends an http request to the port specified in the url

Environment

Im indirectly using axios@0.21.1 (start-server-and-test -> wait-on -> axios@0.21.1).

  • Axios Version [0.21.1
  • Adapter HTTP
  • Node.js Version v12.8.0 and v15.8.0
  • OS: macOS 10.15.6

Additional context/Screenshots

Error:

Error: connect ECONNREFUSED 127.0.0.1:80
    at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1056:14) {
  errno: 'ECONNREFUSED',
  code: 'ECONNREFUSED',
  syscall: 'connect',
  address: '127.0.0.1',
  port: 80,
  config: {
    url: 'http://localhost:8080',
    method: 'get',
    headers: {
      Accept: 'text/html, application/json, text/plain, */*',
      'User-Agent': 'axios/0.21.1',
      host: 'localhost:8080'
    },
    transformRequest: [ [Function: transformRequest] ],
    transformResponse: [ [Function: transformResponse] ],
    timeout: 0,
    adapter: [Function: httpAdapter],
    xsrfCookieName: 'XSRF-TOKEN',
    xsrfHeaderName: 'X-XSRF-TOKEN',
    maxContentLength: -1,
    maxBodyLength: -1,
    httpsAgent: Agent {
      _events: [Object: null prototype],
      _eventsCount: 1,
      _maxListeners: undefined,
      defaultPort: 443,
      protocol: 'https:',
      options: [Object],
      requests: {},
      sockets: {},
      freeSockets: {},
      keepAliveMsecs: 1000,
      keepAlive: false,
      maxSockets: Infinity,
      maxFreeSockets: 256,
      maxCachedSessions: 100,
      _sessionCache: [Object]
    },
    validateStatus: [Function: validateStatus],
    data: undefined
  },
  request: Writable {
    _writableState: WritableState {
      objectMode: false,
      highWaterMark: 16384,
      finalCalled: false,
      needDrain: false,
      ending: false,
      ended: false,
      finished: false,
      destroyed: false,
      decodeStrings: true,
      defaultEncoding: 'utf8',
      length: 0,
      writing: false,
      corked: 0,
      sync: true,
      bufferProcessing: false,
      onwrite: [Function: bound onwrite],
      writecb: null,
      writelen: 0,
      bufferedRequest: null,
      lastBufferedRequest: null,
      pendingcb: 0,
      prefinished: false,
      errorEmitted: false,
      emitClose: true,
      autoDestroy: false,
      bufferedRequestCount: 0,
      corkedRequestsFree: [Object]
    },
    writable: true,
    _events: [Object: null prototype] {
      response: [Function: handleResponse],
      error: [Function: handleRequestError]
    },
    _eventsCount: 2,
    _maxListeners: undefined,
    _options: {
      maxRedirects: 21,
      maxBodyLength: 10485760,
      protocol: 'http:',
      path: 'http://localhost:8080/',
      method: 'GET',
      headers: [Object],
      agent: undefined,
      agents: [Object],
      auth: undefined,
      hostname: null,
      port: null,
      host: null,
      beforeRedirect: [Function: beforeRedirect],
      nativeProtocols: [Object],
      pathname: 'http://localhost:8080/'
    },
    _ended: true,
    _ending: true,
    _redirectCount: 0,
    _redirects: [],
    _requestBodyLength: 0,
    _requestBodyBuffers: [],
    _onNativeResponse: [Function],
    _currentRequest: ClientRequest {
      _events: [Object: null prototype],
      _eventsCount: 7,
      _maxListeners: undefined,
      outputData: [],
      outputSize: 0,
      writable: true,
      _last: true,
      chunkedEncoding: false,
      shouldKeepAlive: false,
      useChunkedEncodingByDefault: false,
      sendDate: false,
      _removedConnection: false,
      _removedContLen: false,
      _removedTE: false,
      _contentLength: 0,
      _hasBody: true,
      _trailer: '',
      finished: true,
      _headerSent: true,
      socket: [Socket],
      connection: [Socket],
      _header: 'GET http://localhost:8080/ HTTP/1.1rn' +
        'Accept: text/html, application/json, text/plain, */*rn' +
        'User-Agent: axios/0.21.1rn' +
        'host: localhost:8080rn' +
        'Connection: closern' +
        'rn',
      _onPendingData: [Function: noopPendingOutput],
      agent: [Agent],
      socketPath: undefined,
      method: 'GET',
      path: 'http://localhost:8080/',
      _ended: false,
      res: null,
      aborted: false,
      timeoutCb: null,
      upgradeOrConnect: false,
      parser: null,
      maxHeadersCount: null,
      _redirectable: [Circular],
      [Symbol(isCorked)]: false,
      [Symbol(outHeadersKey)]: [Object: null prototype]
    },
    _currentUrl: 'http:http://localhost:8080/'
  },
  response: undefined,
  isAxiosError: true,
  toJSON: [Function: toJSON]
}```

ECONNREFUSED - Соединение отклонено сервером

Если вы хотите быстро исправить сообщение «ECONNREFUSED — Соединение отклонено сервером» сообщения об ошибках FileZilla, попробуйте изменить номер порта с 21 (порт FTP по умолчанию) на 22 (порт SFTP по умолчанию) или наоборот, так как это одно из самые распространенные исправления. Если это не сработает или если вам интересно узнать, почему это сработало, продолжайте читать, поскольку мы рассмотрим это исправление и другие общие решения этой проблемы здесь..

FileZilla Econnrefused Соединение отклонено из-за ошибки сервера

FileZilla это популярный, бесплатный и открытый исходный код FTP, FTPS, и SFTP клиент, используемый для загрузки и скачивания файлов. «ECONNREFUSED — Соединение отклонено сервером» — одна из наиболее распространенных ошибок, с которыми могут столкнуться пользователи FileZilla. Вы узнаете, что получили эту ошибку, когда увидите что-то похожее на это после попытки подключения:

Статус: Подключение к некоторому серверу: 21 …
Состояние: попытка подключения не удалась с «ECONNREFUSED — Соединение отклонено сервером».
Ошибка: не удалось подключиться к серверу
Статус: отключен от сервера

Эта ошибка может возникать по разным причинам, поэтому исправление, которое работает для одного человека, может не работать для другого. Ниже мы рассмотрим ряд возможных причин появления этого сообщения и способы их устранения..

Contents

  • 1 Вы используете неправильный порт
  • 2 Явный и неявный FTPS
  • 3 Что-то блокирует соединение
  • 4 Вам нужно добавить «ftp.» В FQDN
  • 5 Вам нужно использовать пассивный режим передачи / активный режим передачи
  • 6 Дайте нам знать, помогли ли эти советы

Вы используете неправильный порт

Если мы используем StackOverflow в качестве ссылки Одно из самых простых решений этой проблемы — одно из самых распространенных. FTP и SFTP служат аналогичным целям, но имеют несколько ключевых отличий. Два основных различия:

  • FTP НЕ зашифрован по умолчанию и использует порт 21 по умолчанию, пока
  • SFTP зашифрован по умолчанию и по умолчанию используется порт 22.

Иногда простое переключение используемого порта может разрешить сообщение ECONNREFUSED. Чаще всего переключение с порта 21 на 22 решает проблему, поскольку порт 21 часто блокируется Интернет-провайдеры и ИТ-команды. Тем не менее, возможно, что переход с порта 22 на порт 21 может решить вашу проблему.

Чтобы изменить номер порта в FileZilla, просто введите числовое значение в Порт: поле, как показано ниже.

FileZilla Изменить порт

Явный и неявный FTPS

Стоит отметить, что явный FTPS часто использует порт 21, но неявный FTPS использует порт 990. Для тех из вас, кто не знаком с двумя типами FTPS, проверьте это FileZilla Wiki. Короче говоря, явный FTPS является более современной версией и начинается со стандартного FTP-соединения, а неявный FTPS прослушивает отдельный порт и предполагает, что соединение зашифровано с самого начала.

Также следует помнить, что администратор сайта мог изменить порт по умолчанию для сайта, и вам нужно будет использовать нестандартный номер порта. Чтобы подтвердить, что это так, обратитесь к администратору сайта (или продолжайте читать, чтобы узнать о некоторых сканерах портов, которые могут помочь).

Что-то блокирует соединение

Как мы упоминали в приведенном выше решении, иногда блокируемый порт может быть основной причиной вашей проблемы. Вы можете сделать следующее, чтобы проверьте, не заблокировано ли ваше соединение:

  • Убедитесь, что ваш межсетевые экраны разрешают исходящий трафик с компьютера, на котором работает клиент FileZilla, на TCP-порт 21 или 22 (или любой другой порт, который вы используете) на файловом сервере.
  • На стороне сервера, убедитесь, что входящие соединения на TCP-порт 21 или 22 (или любой другой порт, который вы используете) разрешается.
  • На стороне сервера, убедитесь, что ваш файловый сервер прослушивает нужный порт. Команда «netstat», которую мы рассмотрели в нашем статья об инструментах устранения неполадок в сети может быть полезно здесь.
  • Убедитесь, что местные межсетевые экраны (например, брандмауэр Windows) или антивирусные программы не мешают вашему соединению или блокировка приложения «filezilla.exe».

Если вам нужно продолжить детализацию и проверить, какие порты открыты на файловом сервере по сети, рассмотрите возможность использования такого инструмента, как птар для устранения неполадок. Если nmap слишком сложен для использования, просмотрите наш полное руководство по Nmap или рассмотрите возможность использования SolarWinds Бесплатный сканер портов. SolarWinds Port Scanner не так совершенен, как nmap, но сам по себе имеет хороший набор функций и с ним легко начать работу..

Примечание: пока наклейки на бампер и футболки скажут вам, что сканирование портов не является незаконным, если вы хотите ошибиться с осторожностью, запускайте сканеры портов только на тех серверах, для которых у вас есть права на сканирование..

Если вы являетесь администратором сервера, у которого возникают проблемы, и вы подозреваете, что конфигурация является частью проблемы, вы можете протестировать другие SFTP / FTPS серверы. Если это так, проверьте наша статья о лучших SFTP / FTPS серверах.

Вам нужно добавить «ftp.» В FQDN

Если вы являетесь администратором сайта и пользуетесь такими услугами, как SiteLock или Sucuri Сайт Брандмауэр для вашего сайта, вам может понадобиться добавить «ftp.» в начале вашего Полное доменное имя (FQDN) установить успешное соединение с помощью FileZilla и других клиентов передачи файлов.

FileZilla Добавить FTP

Престижность HostPapa для этого совета. Если вы ищете другие способы решения этой проблемы или проблем, таких как «Ответ: 421 Слишком много подключений (#) с этого IP-адреса», в частности, связанных со сторонними хостинговыми сайтами, ознакомьтесь с их статья базы знаний по теме.

Вам нужно использовать пассивный режим передачи / активный режим передачи

Ради краткости я не буду углубляться в различия между Пассивный режим передачи и Активный режим передачи. тем не мение, если ни один из советов выше не помог вы решаете проблему и используете FTP или FTPS, переключая режим передачи может помочь.

Чтобы изменить настройку режима активной / пассивной передачи по умолчанию для ваших передач по FTP, выполните следующие действия:

  1. Запустить FileZilla.
  2. щелчок редактировать > настройки.
    FileZilla Редактировать настройки
  3. Под соединение, щелчок FTP.
    FTP-соединение с FileZilla
  4. Выберите переключатель для желаемого режима передачи. Как правило, мы также рекомендуем проверить ‘Разрешить возврат в другой режим передачи при сбое‘Поле (должно быть отмечено по умолчанию). В приведенном ниже примере мы выбираем пассивный режим передачи с помощью ‘Пассивный (рекомендуется)‘переключатель.
    Выбран пассивный режим FileZilla

После внесения этих изменений попробуйте снова подключиться к сайту..

Дайте нам знать, помогли ли эти советы

Это наш список распространенных причин и способов устранения ошибки FileZilla «ECONNREFUSED — Соединение отклонено сервером»

Это сработало для вас? У вас есть другие советы или вопросы, связанные с этой проблемой? Дайте нам знать в разделе комментариев ниже.

Понравилась статья? Поделить с друзьями:
  • Http error connect failed roblox
  • Http error connect fail roblox
  • Http error codes wiki
  • Http error codes iis
  • Http error codes detected during run