ETIMEOUT error | Google Cloud SQL database with NodeJS - mysql

I have created a mysql database on google cloud that I'd like to access from a separate node web application (also running on google cloud). I am testing the connection locally on my computer first, and when I run the following code locally I can successfully establish a connection to my database and see the data in it.
'use strict';
// [START app]
const express = require('express');
const bodyParser = require('body-parser');
const path = require('path');
const app = express();
const mysql = require('mysql');
var connection = mysql.createConnection({
host : 'Cloud SQL IP',
user : 'username',
password : 'password',
database : 'db_name'
});
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))
// parse application/json
app.use(bodyParser.json())
// Make globals.js accessible
app.use(express.static(__dirname + '/'));
app.get('/', (req, res) => {
connection.connect();
connection.query('SELECT * FROM Users', function (error, results, fields) {
if (error) throw error;
console.log(results);
});
connection.end();
res.status(200).send('Hello World!');
});
app.get('/login', (req, res) => {
res.status(200).send();
});
// [START server]
const PORT = process.env.PORT || 8080;
app.listen(PORT, () => {
console.log(`App listening on port ${PORT}`);
console.log('Press Ctrl+C to quit.');
});
// [END app]
However when run this same code in my google app engine (for both debugging on port 8080 and fully deployed on https://myapp.appspot.com) I get the following timeout error:
{ Error: connect ETIMEDOUT
at Connection._handleConnectTimeout (/home/megan_cooper2900/project/node_modules/mysql/lib/Connection.js:419:13)
at Socket.g (events.js:292:16)
at emitNone (events.js:86:13)
at Socket.emit (events.js:185:7)
at Socket._onTimeout (net.js:338:8)
at ontimeout (timers.js:386:14)
at tryOnTimeout (timers.js:250:5)
at Timer.listOnTimeout (timers.js:214:5)
--------------------
at Protocol._enqueue (/home/megan_cooper2900/project/node_modules/mysql/lib/protocol/Protocol.js:145:48)
at Protocol.handshake (/home/megan_cooper2900/project/node_modules/mysql/lib/protocol/Protocol.js:52:23)
at Connection.connect (/home/megan_cooper2900/project/node_modules/mysql/lib/Connection.js:130:18)
at app.get (/home/megan_cooper2900/journeyma/app.js:31:13)
at Layer.handle [as handle_request] (/home/megan_cooper2900/project/node_modules/express/lib/router/layer.js:95:5)
at next (/home/megan_cooper2900/project/node_modules/express/lib/router/route.js:137:13)
at Route.dispatch (/home/megan_cooper2900/project/node_modules/express/lib/router/route.js:112:3)
at Layer.handle [as handle_request] (/home/megan_cooper2900/project/node_modules/express/lib/router/layer.js:95:5)
at /home/megan_cooper2900/project/node_modules/express/lib/router/index.js:281:22
at Function.process_params (/home/megan_cooper2900/project/node_modules/express/lib/router/index.js:335:12)
errorno: 'ETIMEDOUT',
code: 'ETIMEDOUT',
syscall: 'connect',
fatal: true }
Why is this not working on the Google App Engine application?

In your connection configuration for mysql,host does not work on App Engine. You have to use socketPath . socketPath is the path to a unix domain socket to connect to. When used host and port are ignored. (transferred knowledge from using Loopback on App Engine flex. it had me banging my head for days lol). It's value is your Cloud SQL Instance connection name
so in your case, it should look like this: /cloudsql/my-project-12345:us-central1:mydatabase
var connection = mysql.createConnection({
socketPath : '/cloudsql/my-project-12345:us-central1:mydatabase',
user : 'username',
password : 'password',
database : 'db_name'
});
It's a similar process if you're using Postgres on GCloud which is answered here

I also did faced the same issue and I was using Kubernetes pods to access my CloudSQL instance. I got a fix by increasing the timeout in the configuration.
cloudSqlConfig: {
connectionLimit: 10,
host: 'your-host-ip',
user: process.env.DB_USERNAME,
password: process.env.DB_PASSKEY,
database: 'myDB',
connectTimeout: 20000,
waitForConnections: true,
queueLimit: 0
},

Related

How to connect not to local MySQL db (PHPMyAdmin) by using React.js?

I am pretty new at Node.js, and I have existing database uploaded to Dreamhost, which has database PhpMyAdmin. I have created new React application, and by using my server folder I am trying to connect to that database. I am using Windows 10, and I run at http://127.0.0.1:5000/. This is my code:
const express = require("express");
const bodyParser = require("body-parser");
const mysql = require("mysql");
const app = express()
const port = process.env.PORT || 5000
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())
// MySQL
const pool = mysql.createPool({
connectionLimit: 10,
user: "root",
host: '127.0.0.1',
password: "password",
database: "testdb_org"
})
// Get all info
app.get('/', (req, res) => {
pool.getConnection((err, connection) => {
res.send('TEST '+ JSON.stringify(err))
/*if (err) throw err
console.log(`Connected as id ${connection.threadId}`)
connection.query('SELECT * from users', (err, rows) => {
connection.release() // Return the connection to pool
if (!err) {
res.send(rows)
} else {
console.log(err)
}
})*/
})
})
app.listen(port, () => console.log(`Listen on port ${port}`))
res.send gives me following error:
{"code":"ER_ACCESS_DENIED_ERROR","errno":1045,"sqlMessage":"Access denied for user 'root'#'localhost' (using password: YES)","sqlState":"28000","fatal":true}
And when I open comment brackets it gives me following console error:
if (err) throw err
^
Error: connect ECONNREFUSED 127.0.0.1:3306
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1146:16)
--------------------
at Protocol._enqueue (C:\Users\*\Documents\project\server\node_modules\mysql\lib\protocol\Protocol.js:144:48)
at Protocol.handshake (C:\Users\*\Documents\project\server\node_modules\mysql\lib\protocol\Protocol.js:51:23)
at PoolConnection.connect (C:\Users\*\Documents\project\server\node_modules\mysql\lib\Connection.js:116:18)
at Pool.getConnection (C:\Users\*\Documents\project\server\node_modules\mysql\lib\Pool.js:48:16)
at C:\Users\*\Documents\project\server\app.js:24:10
at Layer.handle [as handle_request] (C:\Users\*\Documents\project\server\node_modules\express\lib\router\layer.js:95:5)
at next (C:\Users\*\Documents\project\server\node_modules\express\lib\router\route.js:144:13)
at Route.dispatch (C:\Users\*\Documents\project\server\node_modules\express\lib\router\route.js:114:3)
at Layer.handle [as handle_request] (C:\Users\*\Documents\project\server\node_modules\express\lib\router\layer.js:95:5)
at C:\Users\*\Documents\project\server\node_modules\express\lib\router\index.js:284:15 {
errno: -4078,
code: 'ECONNREFUSED',
syscall: 'connect',
address: '127.0.0.1',
port: 3306,
fatal: true
}
Ok, the problem that it's not possible with online database and localhost of React.js. For connection I had to download .sql database, insert and run it locally with XAMPP control panel.

connection to a remote mysql database using node

Good mornig to you guys. I want to establish a connection to a remote mysql database using node js. but i am facing this error. I do not know if I wrongly specifies the access path to the db
code
var mysql = require('mysql');
var pool = mysql.createPool({
host: "http://kamerun-it.com/mysql",
connectionLimit : 100,
database: "****",
user: "****",
password: "*****",
multipleStatements: true
});
error
throw err;
^
Error: getaddrinfo ENOTFOUND http://kamerun-it.com/mysql
at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:60:26)
--------------------
at Protocol._enqueue (F:\kamerun it\aspi-api\node_modules\mysql\lib\protocol\Protocol.js:144:48)
at Protocol.handshake (F:\kamerun it\aspi-api\node_modules\mysql\lib\protocol\Protocol.js:51:23)
at PoolConnection.connect (F:\kamerun it\aspi-api\node_modules\mysql\lib\Connection.js:119:18)
at Pool.getConnection (F:\kamerun it\aspi-api\node_modules\mysql\lib\Pool.js:48:16)
at Object. (F:\kamerun it\aspi-api\app\model\db.js:16:8)
at Module._compile (internal/modules/cjs/loader.js:956:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:973:10)
at Module.load (internal/modules/cjs/loader.js:812:32)
at Function.Module._load (internal/modules/cjs/loader.js:724:14)
at Module.require (internal/modules/cjs/loader.js:849:19) {
errno: 'ENOTFOUND',
code: 'ENOTFOUND',
syscall: 'getaddrinfo',
hostname: 'http://kamerun-it.com/mysql',
fatal: true
}
You probably have an error in your config with the host URL.
Here's a working example with a connection to a remote MySQL:
const mysql = require("mysql");
const connection = mysql.createPool({
host: "remotemysql.com",
user: "aKlLAqAfXH",
password: "PZKuFVGRQD",
database: "aKlLAqAfXH"
});
connection.query(
"SELECT hexcode FROM colours WHERE precedence = 2",
(err, result) => {
err ? console.log(err) : console.log(result[0].hexcode);
}
);
and here's one with mistaken host parameter:
const mysql = require("mysql");
const connection = mysql.createPool({
host: "WRONGremotemysql.com",
user: "aKlLAqAfXH",
password: "PZKuFVGRQD",
database: "aKlLAqAfXH"
});
connection.query(
"SELECT hexcode FROM colours WHERE precedence = 2",
(err, result) => {
err ? console.log(err) : console.log(result[0].hexcode);
}
);
The second one returns the same ENOTFOUND error.
Check if that's the correct URL, if the database can be accessed remotely and via which port you can use it.

Unable to connect to MySql server from Node.js

I am new to MySQL and cannot seem to connect to the server from Node.js. Also, I am on windows, not UNIX.
I am able to connect to the server using sqlcmd logged into the user I created for node. I have also enabled TCP/IP and named pipes.
const express = require("express");
const mysql = require("mysql");
const app = express();
const sqlServer = mysql.createConnection({
server: "127.0.0.1",
port: "1433",
user: "MeetMe",
password: "dOI9Zham1f5xOJAvweUIvuWlc"
});
const SELECT_ALL_QUERY = "SELECT * FROM Accounts";
sqlServer.connect(function(err) {
console.log("Connected to sql server");
if (err) throw err;
});
app.get("/", (req, res) => {
sqlServer.query(SELECT_ALL_QUERY, function(err, results, fields) {
if (err) throw err;
console.log(results);
});
res.send("Hello world");
});
app.listen(4000);
console.log("Server running on port 4000");
The program always throws an error during sqlServer.connect().
C:\dev\Webapps\meet-me\server.js:16
if (err) throw err;
^
Error: read ECONNRESET
at TCP.onStreamRead (internal/stream_base_commons.js:111:27)
--------------------
at Protocol._enqueue (C:\dev\Webapps\meet-me\node_modules\mysql\lib\protocol\Protocol.js:144:48)
at Protocol.handshake (C:\dev\Webapps\meet-me\node_modules\mysql\lib\protocol\Protocol.js:51:23)
at Connection.connect (C:\dev\Webapps\meet-me\node_modules\mysql\lib\Connection.js:119:18)
at Object.<anonymous> (C:\dev\Webapps\meet-me\server.js:14:11)
at Module._compile (internal/modules/cjs/loader.js:701:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:712:10)
at Module.load (internal/modules/cjs/loader.js:600:32)
at tryModuleLoad (internal/modules/cjs/loader.js:539:12)
at Function.Module._load (internal/modules/cjs/loader.js:531:3)
at Function.Module.runMain (internal/modules/cjs/loader.js:754:12)
MySQL's default port number is 3306.
Your createConnection options object mentions port 1433. That's the default port for Microsoft SQL server. Try removing the port element from that object. Or, if that doesn't work, change it to 3306.
I realized there is a difference in MicrosoftSQL and MySQL. Thank you for everyone that tried to help!

Node and MySQL connection to database

I need t o provide the MySQL connection for modules, so I provide the code like this:
var express = require('express');
var mysql = require('mysql')
var app = express();
var connection = mysql.createConnection({
host: '149.xxx.xx.x',
user: 'User',
password: 'Password',
database: 'DataBase',
port: 1443,
});
connection.connect(
function(error) {
console.log(error.code); // 'ECONNREFUSED'
console.log(error.fatal); // true
console.log(error.sql);
console.log(error.sqlMessage);
}
);
and after some time (about 1-2 minutes) I received an error from those console.logs:
ECONNRESET
true
undefined
undefined
I think maybe it's the timeout because of my "nonactivity", but when I'm trying to do the query the errors are the same.
Have any idea what is wrong? I checked it from DataGrip and the data are correct.
Ok, I found one small bug here. The database is MS SQL Server (microsoft). I'm trying now using the library called mssql to connect to that database, provide some code:
var config = {
server: "149.xxx.xx.x",
database: "Database",
user: "User",
password: "Password",
connectionTimeout: 300000,
requestTimeout: 300000,
pool: {
idleTimeoutMillis: 300000,
max: 100
}
};
function getEmp() {
var connection = new sql.Connection(config);
var req = new sql.Request(connection);
connection.connect(function (error) {
if(error) {
console.log(error);
return;
}
req.query('Procedure', function(err, data) {
if (err) {
console.log(err);
} else {
console.log(data);
}
connection.close();
});
});
}
getEmp();
and I receive the error:
{ ConnectionError: Failed to connect to 149.xxx.xx.x:1433 - connect ETIMEDOUT 149.xxx.xx.x:1433
at Connection.<anonymous> (/Users/phuzarski/Learning/NodeJS/srv-express/node_modules/mssql/lib/tedious.js:353:25)
at Connection.g (events.js:292:16)
at emitOne (events.js:96:13)
at Connection.emit (events.js:188:7)
at Connection.socketError (/Users/phuzarski/Learning/NodeJS/srv-express/node_modules/tedious/lib/connection.js:791:12)
at Socket.<anonymous> (/Users/phuzarski/Learning/NodeJS/srv-express/node_modules/tedious/lib/connection.js:33:15)
at emitOne (events.js:96:13)
at Socket.emit (events.js:188:7)
at emitErrorNT (net.js:1277:8)
at _combinedTickCallback (internal/process/next_tick.js:80:11)
name: 'ConnectionError',
message: 'Failed to connect to 149.xxx.xx.x:1433 - connect ETIMEDOUT 149.xxx.xx.x:1433',
code: 'ESOCKET' }
For sure the data are correct- DataGrip is connecting fine here.
I found at google the similar problem, the problem was Disabled TCP/IP. I checked this one and it's Enabled with this port 1443.

Node Js : MYSQL is not connecting

I am new to node.js, so i am stuck at this point. I have tried to learn it from these sites Code Mentor and Github
Till now i have done this :
var mysql = require('mysql');
var app = express();
// Database operations
var connection = mysql.createConnection({
host : 'localhost',
port : '8888',
user : 'sharad',
password : 'teks',
dbName : 'FirstDataBase'
});
connection.connect(function (error) {
if (error){
console.error('error connecting :' + error.stack);
return;
}
console.log('Connected as id :'+ connection.threadId);
});
app.get("/",function(request,response){
console.log(' saving');
var post = {from:'me', to:'you', msg:'hi'};
connection.query('INSERT INTO FirstDataBase SET ?', post, function(err, result) {
if (err) throw err;
});
});
app.get("/",function(request,response){
connection.query('SELECT * from FirstDataBase', function(err, rows, fields) {
connection.end();
if (!err)
console.log('The solution is: ', rows);
else
console.log('Error while performing Query.');
});
});
app.listen(8888);
I can not see any log i am printing in my code. Any help would be appreciated. Thanks
Edits :
Error i get if i remove last line app.listen(8888);
error connecting :Error: connect ECONNREFUSED 127.0.0.1:8888
at Object.exports._errnoException (util.js:907:11)
at exports._exceptionWithHostPort (util.js:930:20)
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1077:14)
--------------------
at Protocol._enqueue (/Users/Admin/IdeaProjects/FirstNodeJS/node_modules/mysql/lib/protocol/Protocol.js:141:48)
at Protocol.handshake (/Users/Admin/IdeaProjects/FirstNodeJS/node_modules/mysql/lib/protocol/Protocol.js:52:41)
at Connection.connect (/Users/Admin/IdeaProjects/FirstNodeJS/node_modules/mysql/lib/Connection.js:136:18)
at Object.<anonymous> (/Users/Admin/IdeaProjects/FirstNodeJS/app.js:40:12)
at Module._compile (module.js:409:26)
at Object.Module._extensions..js (module.js:416:10)
at Module.load (module.js:343:32)
at Function.Module._load (module.js:300:12)
at Function.Module.runMain (module.js:441:10)
at startup (node.js:139:18)
I resolve this issue like this
install mysql:
npm install mysql
var mysql = require('mysql');
let connection = mysql.createConnection({
host: 'localhost',
user: 'root',
port: '8888', /* port on which phpmyadmin run */
password: 'root',
database: 'dbname',
socketPath: '/Applications/MAMP/tmp/mysql/mysql.sock' //for mac and linux
});
connection.connect(function(err) {
if (err) {
return console.error('error: ' + err.message);
}
console.log('Connected to the MySQL server.');
});
I resolved my problem by installing MAMP and using fields provided by MAMP.
try this
var connection = mysql.createConnection({
host : 'localhost',
user : 'xxxxx',
password : 'xxxxx',
database : 'xxx'
});
connection.connect();