Ошибка connect etimedout node js

I train myslef with NodeJS and tried a simple GET call.
Here is my code:

var http = require('http');

var options = {
    host: 'www.boardgamegeek.com',
    path: '/xmlapi/boardgame/1?stats=1',
    method: 'GET'
}

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

request.on('error', function (e) {
    console.log('Problem with request: ' + e.message);
});

request.end();

The URL called seems to work in my browser https://www.boardgamegeek.com/xmlapi/boardgame/1?stats=1

Anyway, I’ve got Problem with request: connect ETIMEDOUT when I run the code and I have no idea how to fix it.

What could cause this error ? Is it my code or is it a network/proxy issue?

asked Oct 26, 2015 at 16:17

Alex's user avatar

2

When behind a proxy you need to make the following modifications (as explained in this answer):

  • put the proxy host in the host parameter
  • put the proxy port in the port parameter
  • put the full destination URL in the path parameter :

Which gives:

var options = {
    host: '<PROXY_HOST>',
    port: '<PROXY_PORT>',
    path: 'http://www.boardgamegeek.com/xmlapi/boardgame/1?stats=1',
    method: 'GET',
    headers: {
        Host: 'www.boardgamegeek.com'
    }
}

Alex's user avatar

Alex

2,9278 gold badges37 silver badges56 bronze badges

answered Oct 26, 2015 at 16:58

sdabet's user avatar

sdabetsdabet

18.4k11 gold badges89 silver badges158 bronze badges

3

In my case it was because of http but not https as required

answered Nov 6, 2020 at 13:15

cane's user avatar

canecane

8921 gold badge10 silver badges17 bronze badges

If this error occurs while using POSTMAN.

So, when you call a request in Postman and the API requires your VPN to be up before you can make a successful call. You will need to connect or reconnect your VPN.

In my case, I was working on a company’s laptop. I found out it was the VPN that was down.

answered Mar 24, 2022 at 16:50

Seunara's user avatar

SeunaraSeunara

1571 gold badge1 silver badge9 bronze badges

I was facing this issue on Ubuntu Server while maintaining a node instance on PM2. Basically after restarting the instance after taking the pull I was getting the same error on initial connection of mySQL inside the code.

Error: connect ETIMEDOUT
at Connection._handleConnectTimeout (/home/deam_server/node_modules/mysql/lib/Connection.js:419:13)
at Object.onceWrapper (events.js:275:13)
at Socket.emit (events.js:182:13)
at Socket.EventEmitter.emit (domain.js:442:20)
at Socket._onTimeout (net.js:447:8)
at ontimeout (timers.js:427:11)
at tryOnTimeout (timers.js:289:5)
at listOnTimeout (timers.js:252:5)
at Timer.processTimers (timers.js:212:10)

Though the same code was running perfectly on my local machine.
After that I used «df» command which helped me to realise that my root directory was 100% occupied. I allotted some memory to the root directory and the restarted the node instance and then it started working fine.

answered Aug 27, 2018 at 15:10

Rishikesh Chandra's user avatar

The following change with the request worked for me:

 var options = {
         proxy:'PROXY URL', 
         uri: 'API URL',
         method: 'GET' 
         }
 request(options, function (err, response, body) {
     if(err){
        console.log('error:', err);
       } else {
     console.log('body:', body);
      }
   });

answered Mar 12, 2019 at 21:37

hema's user avatar

In my case it was a misconfigured subnet. Only one of the 2 subnets in the ELB worked. But my client kept trying to connect to the misconfigured one.

answered Nov 15, 2019 at 4:11

M.Vanderlee's user avatar

M.VanderleeM.Vanderlee

2,8572 gold badges19 silver badges16 bronze badges

if you have URL
like :

  URL: 'localhost:3030/integration', 

The URL above cause some issues because HTTP does not exist at the beginning of URL so Just change it to it should work.

URL: 'http://localhost:3030/integration', 
  

answered Sep 13, 2020 at 9:03

Yazan Najjar's user avatar

Yazan NajjarYazan Najjar

1,86016 silver badges10 bronze badges

In my case, I was getting this error because the request body of my post api was very large.

answered Jun 16, 2022 at 8:00

Deepak's user avatar

DeepakDeepak

3,1342 gold badges24 silver badges24 bronze badges

Sometimes it can simply be because your internet is down.

answered Feb 14 at 18:54

Mansvini'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:

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:

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:

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......');
});
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......');
});
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:

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);
  }
});
[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);
});
[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;
});
[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);
});
[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;
});
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!

Author's avatar

Article by

Ayooluwa Isaiah

Ayo is the Head of Content at Better Stack. His passion is simplifying and communicating complex technical ideas effectively. His work was featured on several esteemed publications including LWN.net, Digital Ocean, and CSS-Tricks. When he’s not writing or coding, he loves to travel, bike, and play tennis.

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

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.

Всем привет, устал уже от этой ошибки может тут поможете решить? Что в нём не так?
Непосредственно ошибка

Error: connect ETIMEDOUT
    at PoolConnection.Connection._handleConnectTimeout (C:\Users\crazy\Desktop\larp\larp-server\node_modules\mysql\lib\Connection.js:409:13)
    at Object.onceWrapper (events.js:420:28)
    at Socket.emit (events.js:314:20)
    at Socket._onTimeout (net.js:482:8)
    at listOnTimeout (internal/timers.js:554:17)
    at processTimers (internal/timers.js:497:7)
    --------------------
    at Protocol._enqueue (C:\Users\crazy\Desktop\larp\larp-server\node_modules\mysql\lib\protocol\Protocol.js:144:48)
    at Protocol.handshake (C:\Users\crazy\Desktop\larp\larp-server\node_modules\mysql\lib\protocol\Protocol.js:51:23)
    at PoolConnection.connect (C:\Users\crazy\Desktop\larp\larp-server\node_modules\mysql\lib\Connection.js:116:18)
    at Pool.getConnection (C:\Users\crazy\Desktop\larp\larp-server\node_modules\mysql\lib\Pool.js:48:16)
    at Object.mysql.executeQuery (C:\Users\crazy\Desktop\larp\larp-server\packages\modules\mysql.js:207:14)
    at init (C:\Users\crazy\Desktop\larp\larp-server\packages\index.js:68:15)
    at Object.<anonymous> (C:\Users\crazy\Desktop\larp\larp-server\packages\index.js:146:1)
    at Module._compile (internal/modules/cjs/loader.js:1076:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1097:10)
    at Module.load (internal/modules/cjs/loader.js:941:32) {
  errorno: 'ETIMEDOUT',
  code: 'ETIMEDOUT',
  syscall: 'connect',
  fatal: true
    at processTimers (internal/timers.js:497:7)
    --------------------
    at Protocol._enqueue (C:\Users\crazy\Desktop\larp\larp-server\node_modules\mysql\lib\protocol\Protocol.js:144:48)
    at Protocol.handshake (C:\Users\crazy\Desktop\larp\larp-server\node_modules\mysql\lib\protocol\Protocol.js:51:23)
    at PoolConnection.connect (C:\Users\crazy\Desktop\larp\larp-server\node_modules\mysql\lib\Connection.js:116:18)
    at Pool.getConnection (C:\Users\crazy\Desktop\larp\larp-server\node_modules\mysql\lib\Pool.js:48:16)
    at Pool.query (C:\Users\crazy\Desktop\larp\larp-server\node_modules\mysql\lib\Pool.js:202:8)
    at Object.mysql.executeQueryOld (C:\Users\crazy\Desktop\larp\larp-server\packages\modules\mysql.js:244:14)
    at Object.mysql.executeQuery (C:\Users\crazy\Desktop\larp\larp-server\packages\modules\mysql.js:198:19)
    at Object.vehicleInfo.loadAll (C:\Users\crazy\Desktop\larp\larp-server\packages\modules\vehicleInfo.js:8:11)
    at init (C:\Users\crazy\Desktop\larp\larp-server\packages\index.js:73:21)
    at Object.<anonymous> (C:\Users\crazy\Desktop\larp\larp-server\packages\index.js:146:1) {
  errorno: 'ETIMEDOUT',
  code: 'ETIMEDOUT',
  syscall: 'connect',
  fatal: true
}

Сам код

const pool = mysql2.createPool({
    host: host,
    //socketPath: '/var/run/mysqld/mysqld.sock', //Если хочешь напрямую по сокету подключать, ускоряет немного всю хуйню
    user: dbuser,
    password: password,
    database: database,
    port: 3306,
    waitForConnections: true,
    connectionLimit: 500,
    queueLimit: 0
});

pool.on('connection', function (connection) {
    connection.query("SET SESSION `sql_mode` = ''");
    connection.query("SET GLOBAL `connect_timeout` = '31536000'");
    connection.query("SET GLOBAL `wait_timeout` = '31536000'");
    connection.query("SET GLOBAL `interactive_timeout` = '28800'");
    console.log('New MySQL connection id: ' + connection.threadId);
});

mysql.executeQuery = async function (query, values, callback) {
    const preQuery = new Date().getTime();
    try {
        if (query.indexOf('DELETE') === 0 /*|| query.indexOf('UPDATE') === 0*/ || query.indexOf('INSERT') === 0 || query.indexOf('SELECT') === 0) {
            mysql.executeQueryOld(query, values, function (err, rows, fields) {
                try {
                    if (callback)
                        callback(err, rows, fields);
                }
                catch (e) {}
            });
            return;
        }
        pool.getConnection(function (err, connection) {
            try {
                if(!err) {
                    connection.query({
                        sql: query
                    }, values, function (err, rows, fields) {
                        
                        const postQuery = new Date().getTime();
                        methods.debug(query, `Async time: ${postQuery - preQuery}ms`);
                        try {
                            if (!err) {
                                if (callback)
                                    callback(null, rows, fields);
                            } else {
                                console.log("[DATABASE ASYNC | ERROR | " + mysql.getTime() + "]", query, err);
                                if (callback)
                                    callback(err);
                            }
                        }
                        catch (e) {}
                    });
                } 
                else throw err;
                connection.release();
            }
            catch (e) {
                console.log(e);
            }
        });
    } catch (e) {
        console.log('DBERROR', e);
    }
};

I fought this same error for about 2 days when using Nodejs mysql module in AWS Lambda when trying to connect to a database in a VPC. It is a very tough problem to debug because Lambda’s logging is so flaky (depending on the error you may not get log data at all).

@dougwilson had the right thought in that it is most likely is a networking issue.

@hagen is certainly right that all those factors have to be worked out first before it will even consider working. Also, if you are accessing a service that is not in the same VPC as your Lambda function you will need a route to it, probably using a VPC NAT Gateway, NOTE: a VPC Internet Gateway will not work as you might think because Lambda does not allocate a public IP address to its ENI, only a private IP address from one of the VPC subnets you select in Lambda’s «Configuration».

If you can work all that out, which is not easy! Chances are it still will not work if you are using traditional Nodejs code logic. This is due primarily, because Lambda’s have a high start-up delay and automatically passivate and reactive depending on when and how often they are accessed. This causes mysql’s data connection pools to work sometimes and fail other times. Often what you will see is that the mysql connection works fine the first invocation then fails most of the time afterwards. If you see this behavior you are half way to solving the problem as it means you have solved all of the AWS VPC networking issues and are now facing Lambda delay, passivation, reactivation issues. These issues can be fixed by modifying your Nodejs Lambda’s source code logic.

I have tried to provide a simplified example of what you need to do below:

`
const VERSION = «1»;
console.log(«asclepiusrod.net Lambda Tutorial » + VERSION + » starting up…»);
process.env[‘PATH’] = process.env[‘PATH’] + ‘:’ + process.env[‘LAMBDA_TASK_ROOT’];

//CMT You must install below packages first i.e. npm install fs, npm install await, npm install aws-sdk, npm install mysql npm install mysql2

const fs = require(‘fs’);
const Await = require(‘await’);
const AWS = require(‘aws-sdk’);
const mysql = require(‘mysql’);
//const mysql = require(‘mysql2’);

const DATABASE_HOST = process.env[‘DATABASE_HOST’];
const DATABASE_USERNAME = process.env[‘DATABASE_USERNAME’];
const DATABASE_PASSWORD_ENCRYPTED = process.env[‘DATABASE_PASSWORD’];
let DATABASE_PASSWORD;
const DATABASE_SCHEMA = process.env[‘DATABASE_SCHEMA’];
const DATABASE_POOL_LIMIT = process.env[‘DATABASE_POOL_LIMIT’];
const DATABASE_CONNECT_TIMEOUT_MILLI = process.env[‘DATABASE_CONNECT_TIMEOUT_MILLI’];
const DATABASE_TEST_TABLE = process.env[‘DATABASE_TEST_TABLE’];
const KMS_REGION = new String(process.env[‘KMS_REGION’]);

var mySqlPool;
var AWSEvent;
var AWSContext;
var AWSCallback;
var promise1;
var promise2;
var promise3;
AWS.config.update(KMS_REGION);
//AWS.config.update({region: ‘us-east-1’});

makePromise3();
makePromise2();
makePromise1();

decryptENV();

function makePromise1() {
promise1 = Await(‘DATABASE_PASSWORD’);
promise1.onkeep(function (got) {
console.info(‘[OK] Promise1 kept, creating database connection pool…’);
DATABASE_PASSWORD = got.DATABASE_PASSWORD;
createDBConnectionPool();
testDBConnection();
})
.onfail(function (err) {
console.error(‘[FATAL!] [ERROR!] Promise1 not kept!’ + err, err.stack);
promise2.fail(err);
})
.onresolve(function () {
console.info(‘[INFO] Promise1 resolved.’);
});
}
function makePromise2() {
promise2 = Await(‘isDBTestSuccessful’, ‘isAWSReady’);
promise2.onkeep(function (got) {
console.log(‘[OK] Promise2 kept, database test successful.’);
AWSContext.callbackWaitsForEmptyEventLoop = false;
get(AWSEvent, AWSContext);
})
.onfail(function (err) {
console.error(‘[FATAL!] [ERROR!] Promise2 not kept!’ + err, err.stack);
promise3.fail(err);
})
.onresolve(function () {
console.info(‘[INFO] Promise2 resolved.’);
});
}

function makePromise3() {
promise3 = Await(‘response’);
promise3.onkeep(function (got) {
console.info(‘[OK] Promise3 kept, database test successful.’);
//CMT — export.handler final success return
AWSCallback(null, JSON.stringify(got.response));
console.info(‘[OK] Lambda function completed successfully, ok to to end process once threads finish wrapping up. ADMIN_CODE: 75’);
})
.onfail(function (err) {
console.error(‘[FATAL!] [ERROR!] Promise3 not kept!’ + err, err.stack);
//CMT — export.handler final failure return
AWSCallback(err);
console.error(‘[FATAL!] Lambda function completed unsuccessfully, ok to to end process. ADMIN_CODE: 82’);
})
.onresolve(function () {
console.info(‘[INFO] Promise3 resolved.’);
//CMT — Not sure it is efficent to execute end() and may cause intermittent timesouts to requests — mySqlPool.end();
AWSContext.done();
//CMT — index.js final return
return;
});
}

function decryptENV() {
console.log(‘Decrypting enviroment variables…’);
//Put logic here to keep promise1
}

function createDBConnectionPool() {
try {
if (!mySqlPool)
{
mySqlPool = mysql.createPool({
connectTimeout: DATABASE_CONNECT_TIMEOUT_MILLI,
connectionLimit: DATABASE_POOL_LIMIT,
host: DATABASE_HOST,
user: DATABASE_USERNAME,
password: DATABASE_PASSWORD,
database: DATABASE_SCHEMA,
authSwitchHandler: ‘mysql_native_password’
});

        mySqlPool.on('connection', function (connection) {
            console.log('mySqlPool established a database connection.');
        });

        mySqlPool.on('error', function (err) {
            console.warn('mySqlPool database connection pool failed!' + err, err.stack);
            promise2.fail(err);
        });
    }
    return mySqlPool;
} catch (err)
{
    console.error("FATAL! ERROR! Cannot create connection pool!  Verify that your credentials in ENV are correct. ADMIN_CODE: 122 ", err);
    promise2.fail(err);
}

}

function testDBConnection() {
console.log(«Connecting to database…»);
try {
if (!mySqlPool)
{
createDBConnectionPool();
console.log(«mySqlPool not ready, requesting pool initialization…»);
}
mySqlPool.getConnection(function (err, con) {
if (err)
{
console.warn(«WARN! Unable to create database connection pool! Will try again later. ADMIN_CODE: 138 ; «, err);
//CMT Do not fail promise here as you might think — promise2.fail(err);
return false;
} else
{
console.log(«SUCCESS. MySql database pool online.»);
promise2.keep(‘isDBTestSuccessful’, true);
con.release();
return true;
}
});
} catch (err)
{
console.error(«[FATAL!] [ERROR!] Cannot connect to database! Verify that your credentials in ENV are correct and that database is online and you have a route. ADMIN_CODE: 151 «, err);
promise2.fail(err);
return false;
}
}

/*

  • //CNT Uncomment and comment exports.handler line to test local

function exitNow(err)
{
process.exit(1);
return err;
}

function t1(event, context, callback) {
*/

exports.handler = function (event, context, callback) {
AWSEvent = event;
AWSContext = context;
AWSCallback = callback;

makePromise3();
if (!testDBConnection())
{        
    makePromise2();
}
promise2.keep('isAWSReady', true);

}

function get(myAWSEvent, myAWSContext) {
var myResponse = null;
var header = «»;
var footer = «»;
var welcome = «

Welcome to Lambda Tutorial vR» + VERSION + «.»;
welcome += «

App Server is online.

Database server is «;
try {
mySqlPool.getConnection(function (err, con) {
if (err)
{
console.error(«FATAL! ERROR! Could not create connection pool or port not open! ADMIN_CODE: 192 ; «, err);
console.warn(«Database is OFFLINE.»);

            myResponse = header + welcome + footer;
            promise3.keep('response', myResponse);
            return;
        } else
        {
            console.log("Accessing database...");
            var sql = "SELECT * FROM " + DATABASE_TEST_TABLE + " LIMIT 1 ;";
            con.query(sql, function (err, rows, fields) {
                if (err)
                {
                    console.warn("Database is OFFLINE.");
                    console.error("[FATAL!] [ERROR!] Executing SELECT query on database. ADMIN_CODE: 207 ; ", err);
                    welcome += "offline! Please try again later. ";                        
                } else {
                    console.info("Database is ONLINE.");
                    welcome += "online. <p>Congratulation! You have fixed the problem. Lambda is working!";
                }
                myResponse = header + welcome + footer;
                promise3.keep('response', myResponse);
                con.release();
                return;
            });
        }
    });
} catch (err) {
    console.error("[FATAL!] [ERROR!] Could not create connection pool or port not open! ADMIN_CODE: 221 ; ", err);
    console.warn("Database is OFFLINE.");
    welcome += "offline! <p>Please try again later. ";
    
    myResponse = header + welcome + footer;
    promise3.keep('response', myResponse);
    return;
}

}

`

Good Luck!
Sam

When you are using npm install command to install some packages, you may get this error: RequestError: connect ETIMEDOUT. In this tutorial, we will introduce you how to fix it.

We should set registry url for npm.

Here is an example:

We plan to set registry to https://registry.npm.taobao.org

Method 1

Run command below:

npm --registry https://registry.npm.taobao.org info underscore

Method 2

Run command below:

npm config set registry https://registry.npm.taobao.org 
npm info underscore

Then you will find a response.

set node.js npm registry

Method 3

Edit file ..nodejs\node_modules\npm\npmrc

and add content below at the end of npmrc file.

registry = https://registry.npm.taobao.org

Понравилась статья? Поделить с друзьями:
  • Ошибка couldn t load image specialty new
  • Ошибка couldn t load filesyscheck cfg
  • Ошибка couldn t load default cfg
  • Ошибка could not resolve hostname
  • Ошибка could not resolve dns name mikrotik