Cannot connect cloud function to Cloud SQL - javascript

I am trying to fetch data from GCP cloud MySQL database using a cloud function. The cloud function is written in Nodejs. This function is making a query to fetch data from the database. I have created a Serverless VPC connector that I have attached to function and MySQL. MYSQL has private IP enabled. However I get the below error:
Error: connect ETIMEDOUT at
PoolConnection.Connection._handleConnectTimeout
(/workspace/node_modules/mysql/lib/Connection.js:409:13) at
Object.onceWrapper (events.js:519:28) at Socket.emit
(events.js:400:28) at Socket.emit (domain.js:537:15) at
Socket._onTimeout (net.js:495:8) at listOnTimeout
(internal/timers.js:557:17) at processTimers
(internal/timers.js:500:7) Error: connect ETIMEDOUT at
PoolConnection.Connection._handleConnectTimeout
(/workspace/node_modules/mysql/lib/Connection.js:409:13) at
Object.onceWrapper (events.js:519:28) at Socket.emit
(events.js:400:28) at Socket.emit (domain.js:537:15) at
Socket._onTimeout (net.js:495:8) at listOnTimeout
(internal/timers.js:557:17) at processTimers
(internal/timers.js:500:7)
Below is my Cloud function code:
const mysql = require('mysql');
const mysqlConfig = {
connectionLimit: 1,
host: '10.217.208.5',
port: '3306',
user: 'root',
password: 'tmc',
database: 'tmc'
};
let mysqlPool;
exports.helloWorld = (req, res) => {
mysqlPool = mysql.createPool(mysqlConfig);
mysqlPool.query(`SELECT * FROM tmc`, function (error, results) {
console.log(error);
console.log(results)
res.status(200).send(results);
});
};
My Cloud SQL instance
Network for private connections:
GCP function VPC connector

In my case it was a firewall issue. I allowed a particular IP and things worked. If u face a similar issue you may also try allowing 0.0.0.0/0 (Just for testing) inside SQL connections settings. 0.0.0.0/0 opens SQL to the world

Related

Error: connect ETIMEDOUT xxx.xx.xxx.xxx:587 Nodemailer script stopped working with outlook throws

A few months ago I created this script to help me send multiple mails at once instead of sending them one by one, and it was working perfectly till now.
For this script, I've used dotenv, nodemailer, and nodemon (only in development, when I finished it I started using npm run start to run it)
(function main() {
const { contacts } = contacts_list;
try {
const { MAIL_ACCOUNT, MAIL_PASSWORD } = process.env;
const transport = nodemailer.createTransport({
// Uses 'pool' attribute: The same connection is used to send up to 100 mails before being disposed.
pool: true,
// Sets the number of max connections per transport. Microsoft accepts up to 1 parallel connection for the same client.
maxConnections: 1,
logger: true,
debug: true,
service: "hotmail",
auth: {
user: MAIL_ACCOUNT,
pass: MAIL_PASSWORD
},
tls: { rejectUnauthorized: false }
})
// Change mail parameters such as subject, recipients, content, etc
const mailParams = {
from: `test <${MAIL_ACCOUNT}>`,
to: '',
attachments: [],
subject: `test`,
text: `test`,
html: `<h1>test</h1>`
}
// Mail every contact once at a time with its corresponding attachments
contacts.forEach(async (contact) => {
mailParams.to = contact.email;
mailParams.attachments = [...contact.attachments];
await transport.sendMail(mailParams);
})
} catch (err) {
console.error(err);
}
})();
I've already scanned for blocked ports, disabled firewall when trying to use it and antivirus as well. None of these approaches worked.
It throws the following error:
node:internal/process/promises:246
triggerUncaughtException(err, true /* fromPromise */);
^
Error: connect ETIMEDOUT xxx.xx.xxx.xxx:587
at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1161:16) {
errno: -4039,
code: 'ESOCKET',
syscall: 'connect',
address: 'xxx.xx.xxx.xxx',
port: 587,
command: 'CONN'
}
Logger prints the following lines:
[2022-02-03 01:39:22] DEBUG Creating transport: nodemailer (6.7.2; +https://nodemailer.com/; SMTP (pool)/6.7.2[client:6.7.2])
[2022-02-03 01:39:22] DEBUG Sending mail using SMTP (pool)/6.7.2[client:6.7.2]
[2022-02-03 01:39:22] DEBUG Sending mail using SMTP (pool)/6.7.2[client:6.7.2]
[2022-02-03 01:39:22] INFO [#1] Created new pool resource #1
[2022-02-03 01:39:22] DEBUG [#1] Assigned message <567cc726-524b-0bda-5a52-698109ae7d78#hotmail.com> to #1 (1)
[2022-02-03 01:39:22] DEBUG [nHXJGQWMbA] Resolved smtp.live.com as xxx.xx.xxx.xxx [cache miss]
[2022-02-03 01:39:43] ERROR [nHXJGQWMbA] connect ETIMEDOUT xxx.xx.xxx.xxx:587
[2022-02-03 01:39:43] ERROR [#1] Pool Error for #1: connect ETIMEDOUT xxx.xx.xxx.xxx:587
[2022-02-03 01:39:43] ERROR Send Error: connect ETIMEDOUT xxx.xx.xxx.xxx:587
[2022-02-03 01:39:43] DEBUG [nHXJGQWMbA] Closing connection to the server using "destroy"
[2022-02-03 01:39:43] INFO [#1] Connection #1 was closed
If you know how to solve it, i'll be very grateful if you lend me a hand!
SOLUTION:
Finally, I found the solution thanks to #Marco Strahilov 's answer in other post. When instantiating the transport, set the service property to 'smtp-mail.outlook.com' instead of hotmail. I don't know for sure why 'hotmail' stopped working nor why 'stmp-email.outlook.com' works now.
go to
Settings => View All Outlook settings => Mail => Sync email
here is info for your correct settings IMAP, POP, SMTP
Finally, I found the solution thanks to #Marco Strahilov 's answer in other post.
When instantiating the transport, set the service property to 'smtp-mail.outlook.com' instead of hotmail. I don't know for sure why 'hotmail' stopped working.

Unable to create MongoDB database using Node.js

I am trying to run the below program to create a mongo database using Node.js by running node app.js.
app.js
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://hostname:27017/mydb";
MongoClient.connect(url, function(err, db) {
if (err) throw err;
console.log("Database created!");
db.close();
});
Below is the error I'm getting :-
(node:20815) DeprecationWarning: current Server Discovery and Monitoring engine is deprecated, and will be removed in a future version. To use the new Server Discover and Monitoring engine, pass option { useUnifiedTopology: true } to the MongoClient constructor.
MongoNetworkError: failed to connect to server [hostname_fqdn:27017] on first connect [Error: connect ECONNREFUSED 10.127.45.59:27017
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1134:16) {
name: 'MongoNetworkError'
}]
at Pool.<anonymous> (/root/myfolder/node_modules/mongodb/lib/core/topologies/server.js:438:11)
at Pool.emit (events.js:223:5)
at /root/myfolder/node_modules/mongodb/lib/core/connection/pool.js:562:14
at /root/myfolder/node_modules/mongodb/lib/core/connection/pool.js:995:11
at /root/myfolder/node_modules/mongodb/lib/core/connection/connect.js:32:7
at callback (/root/myfolder/node_modules/mongodb/lib/core/connection/connect.js:280:5)
at Socket.<anonymous> (/root/myfolder/node_modules/mongodb/lib/core/connection/connect.js:310:7)
at Object.onceWrapper (events.js:313:26)
at Socket.emit (events.js:223:5)
at emitErrorNT (internal/streams/destroy.js:92:8) {
name: 'MongoNetworkError'
}
The file/node_modules/package.json all are located in a CentOS Virtual Machine.
You need to start the MongoDB Service after installing.
Edited:
If you have already started service and connecting mongo via terminal, then try to remove mongo lock file (rm /var/lib/mongodb/mongod.lock) and repair mongod (mongod -–repair). Now start mongo service and see if you can connect. I had similar issue with EC2 and Compass and tried above to resolve.

Connection with rest-API and SQL server or Azure

I have a problem with the connection to my database located in Azure, I was attempting to do a connection with a rest-API that I create, to a database that I have in Azure, this database I manage directly from SQL Server, and I can't make a connection with this.
I attempt to connect with another test database in SQL Server.
The rest-API ia create is in NodeJS
var sql = require('mssql');
var dbconfig = {
server:"Fernando\EQUIPO",
user: "<user>",
password: "<password>",
database: "<dbname>",
port: 1433,
option: {
encrypt: false
}
};
function getList() {
var record;
var conn = new sql.ConnectionPool(dbconfig);
conn.connect(function(err){
if(err) throw err;
var req = new sql.Request(conn);
req.query("select * from cliente", function(err, recordset) {
if(err) throw err;
else {
console.log(recordset);
record = recordset;
}
conn.close();
});
});
return record;
}
const { Router } = require('express');
const router = Router();
const _ = require('underscore');
const movies = require('../sample.json');
router.get('/', (req, res) => {
res.send(getList());
});
When I make a "get" to my local host http://localhost:3000/api/movies appears the following message in the console:
GET /api/movies 200 126.188 ms - -
(node:11868) UnhandledPromiseRejectionWarning: ConnectionError: Failed to connect to FernandoEQUIPO:1433 - getaddrinfo ENOTFOUND FernandoEQUIPO
at Connection.tedious.once.err (C:\Users\luisn\Desktop\rest-API\node_modules\mssql\lib\tedious\connection-pool.js:68:17)
at Object.onceWrapper (events.js:286:20)
at Connection.emit (events.js:198:13)
at Connection.socketError (C:\Users\luisn\Desktop\rest-API\node_modules\tedious\lib\connection.js:1258:12)
at _connector.Connector.execute (C:\Users\luisn\Desktop\rest-API\node_modules\tedious\lib\connection.js:1084:21)
at GetAddrInfoReqWrap._dns.default.lookup [as callback] (C:\Users\luisn\Desktop\rest-API\node_modules\tedious\lib\connector.js:152:16)
at GetAddrInfoReqWrap.onlookupall [as oncomplete] (dns.js:68:17)
(node:11868) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:11868) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
Connect to Azure SQL database:
Here's the example code connect to Azure SQL database with REST-API:
Note: the encrypt must be true.
You can get the server name from on Portal:
And you need to add the client IP address to the Azure SQL Server firewall settings:
Then you could connect to the Azure SQL database now. You can reference:Creating a Node.js REST API in Azure
Connect to SQL Server:
Your code is almost correct and need some change:
var sql = require('mssql');
var dbconfig = {
server:"localhost",
user: "<user>",
password: "<password>",
database: "<dbname>",
port: 1433,
option: {
encrypt: false
}
};
Like Abhishek Ranjan said, you should enter your server ip.
Hope this helps.
Welcome to StackOverflow.
ConnectionError: Failed to connect to FernandoEQUIPO:1433 - getaddrinfo ENOTFOUND FernandoEQUIPO
Your error states that it is unable to connect as it could not find a server at the given address.Make sure there is a server runninng and verify connection using some third party app.
Are you sure FernandoEQUIPO gets resolved to a proper hostname ?

Unable to connect remote mysql from nodejs app

Database connection working fine with localhost but not working with remote host.I got the ip from my cpanel that is shared ip. is there anything i am missing?
const db = mysql.createConnection({
host: '195.201.179.80',
user: '****',
password: '****',
database: 'enamme_m-tube'
});
db.connect(function (err) {
if (err) throw err
console.log('Connection Established To Mysql Database')
})
Note: My Node app is running on localhost.
Error :
Error: connect ECONNREFUSED 195.201.179.80:3306
at Object._errnoException (util.js:992:11)
at _exceptionWithHostPort (util.js:1014:20)
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1186:14)
You should to connect to MYSQL under root and send query:
GRANT ALL ON *.* TO <db_user>#<remote_ip> IDENTIFIED BY '<db_user_pass>';
Did your mysqld binding on public IP address? As default mysqld will bind to the UNIX socket. Try adding this in your /etc/my.cnf
[mysqld]
bind-address = <your_public_ip>

error: password authentication failed for user "myuser"

If I have a record in /etc/postgresql/9.4/main/pg_hba.conf which specifically trusts my specific user
# TYPE DATABASE USER ADDRESS METHOD
local all myuser trust
Since I'm on debian I restart postgresql like this
sudo /etc/init.d/postgresql restart
Here is my entire source file testing this out:
const pg = require('pg');
const connectionString = "postgres://myuser:mypassword#localhost/mydbname";
const client = new pg.Client(connectionString);
client.connect();
const query = client.query('SELECT * FROM USERS');
query.on('end', () => { client.end(); });
and this is the error I consistently get:
error: password authentication failed for user "myuser"
at Connection.parseE (/home/myuser/webserver/node_modules/pg/lib/connection.js:539:11)
at Connection.parseMessage (/home/myuser/webserver/node_modules/pg/lib/connection.js:366:17)
at Socket.<anonymous> (/home/myuser/webserver/node_modules/pg/lib/connection.js:105:22)
at emitOne (events.js:96:13)
at Socket.emit (events.js:188:7)
at readableAddChunk (_stream_readable.js:176:18)
at Socket.Readable.push (_stream_readable.js:134:10)
at TCP.onread (net.js:551:20)
It's also worth noting that doing the following works:
psql -h localhost -U myuser mydb
What am I doing wrong here?
As the documentation states, local is only for UNIX socket connections, while you are establishing a TCP connection to localhost.
Use a line like this:
host all myuser 127.0.0.1/32 trust
to trust all connections from localhost using IPv4 (use the adress ::1/128 for IPv6).

Categories