Connection timed out: Nodejs Google App Engine to Cloud MySql - mysql

The code is very basic. Simple nodejs app using mysql.
Error: connect ETIMEDOUT is received when code tries connecting to Google Cloud MySql server (second generation) on google app engine.
However app is able to connect to MySql server from my local machine since IP address of my machine is whitelisted.
App engine application and google cloud server belong to same project in google cloud console. So no extra permissions are required (?)
So I'm failing to understand how to allow app engine to access MySql server.
var express = require('express'),
mysql = require('mysql'),
bodyParser = require('body-parser')
// Application initialization
var connection = mysql.createConnection({
host : 'ip_address',
user : 'root',
password : 'password',
database : 'database_name'
});
var app = express();
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(bodyParser.json());
app.get('/_ah/health', (req, res) => {
res.status(200)
res.send({hello:'world'})
})
app.get('/', function(req, res) {
connection.query('select * from blogs',
function (err, result) {
if (err) throw err;
res.send({result: result});
}
);
});
// Begin listening
app.listen(8080);
console.log("Express server listening");

Using socketPath param while connecting to mysql helped.
var connection = mysql.createConnection({
host : 'ip_address',
user : 'root',
password : 'password',
database : 'database_name'
socketPath: “/cloudsql/projectName:zone:instance-name”
});

Related

Unable to connect React Native app to MySQL database using Node.js. (Error: connect ECONNREFUSED 127.0.0.1:3306)

I am very new to programming so I do apologize if this is a really simple question.
So, I have been trying to connect my React Native application to the MySQL Database using Node and Express server, but I keep on getting the following error (I have checked other stackoverflow questions as well, but nothing has helped):
Error
I have checked my host name and port number multiple times and the all the information seems to be correct. I am not sure what is wrong with the following code:
var express = require("express");
var app = express();
var mysql = require("mysql");
var bodyParser = require("body-parser");
const { application } = require("express");
app.use(bodyParser.json({ type: "application/json" }));
app.use(bodyParser.urlencoded({ extended: true }));
var connection = mysql.createConnection({
host: '127.0.0.1', // Your connection adress (localhost).
port: "3306",
user: "root", // Your database's username.
password: "", // Your database's password.
database: "birthdays", // Your database's name.
});
connection.connect(function (error) {
if (error) console.log(error);
else console.log("connected");
});
// Starting our server.
app.listen(4547, () => {
console.log("Go to http://localhost:4547/dinners so you can see the data.");
});
app.get("/users", function (req, res) {
con.query("select * from users", function (error, rows, fields) {
if (error) console.log(error);
else {
console.log(rows);
res.send(rows);
}
});
});
I run this code by typing "node fileName.js" in the terminal.
I don't know if this is helpful, but I have also connected by MySQL database to MySQL Workbench.
Any help is appreciated!

React Native Access mysql db using express

I need to access my Data from my mysql Database using express, on my server the data is as a json, but when i try to access it i always get 'undefined' and my express server crash
the json i have on the server :
[{"idProjet":1,"nomProjet":"test","dateDebut":"2021-05-18T22:00:00.000Z","nomAuteur":"mathieu","prenomAuteur":"jean","organisme":"idmc"}]
fetching code :
let id = 'id :';
const [data, setData] = useState([]);
useEffect(() => {
fetch('http://localhost:3000/projets')
.then(response => {return response.json()})
.then((json => {console.log(json);setData(json);}))
.catch(error => console.error(error));
console.log(data);
}, []);
Route.js code :
const express = require('express');
const bodyParser = require('body-parser');
const mysql = require('mysql');
const connection = mysql.createPool({
host : 'localhost',
user : 'root',
password : '',
database : 'agora'
});
// Starting our app.
const app = express();
// Creating a GET route that returns data from the 'users' table.
app.get('/projets', function (req, res) {
// Connecting to the database.
connection.getConnection(function (err, connection) {
// Executing the MySQL query (select all data from the 'users' table).
connection.query('SELECT * FROM projet', function (error, results, fields) {
// If some error occurs, we throw an error.
if (error) throw error;
// Getting the 'response' from the database and sending it to our route. This is were the data is.
res.send(results)
});
});
});
// Starting our server.
app.listen(3000, () => {
console.log('Go to http://localhost:3000/projets so you can see the data.');
});
The most common problem for this type of behavior is that you are using react-native on an android emulator. Android Emulator is using an IP-address different from localhost on windows machine. For more information, check here the official documentation.
So you can forward your port on the same port used by the android emulator (10.0.2.2) or you can change the port to 80 so you won't have any problem
You can go check this answer here

Can't connect to mysql (express) with Node.js

Hello Stacksoverflowers,
I have a problem to connect my server.js file to Mysql via Express.
I've already insatlled mysql and express via npm.
when i run my server.js
The only thing it says in my console (MacOS default terminal) is:
"node server running now - using http://localhost:3000"
(I got no errors)
and my webpage also showing correct - "Node Server running - startpage" in the browser.
The problem is that they say nothing like "Connected to the MySQL server" or "Timeout: error messages" ?? (look at #3)
// Dan k
//#1
// My codes from server.js
const express = require('express');
const mysql = require('mysql');
const hostname = "localhost:";
const port = 3000;
//#2
// create connection to DB
const connection = mysql.createConnection({
host: "localhost",
user: 'root',
password: 'root',
port: 3000
});
//#3
// Connect to DB
connection.connect(function(err) {
if (!err) {
console.log('Connected to the MySQL server.');
}
else if (err)
{
return console.error('Timeout: ' + err.message);
}
});
// Routing with Express
const app = express();
//#4
// Startpage (root)
app.get('/', function(request, response){
response.send('Node Server running - startpage...');
response.end();
})
connection.end();
//#5
app.listen(port, (err) => {
if(err) throw err;
console.log("node server running now - using http://"+(hostname)+ .
(port)");
});
I got what is causing the issue. You are using the same port number 3000 to connect to your mysqlDB and at the same time using the same port to run your nodejs application.
This does throw an error but it takes a really long time to throw the error.
So the simple answer here is that the port that you are mentioning in your createConnection() method is incorrect and needs to be changed. This port should be port number on which your mysql DB is running. From the error it is clear that your mysql DB is not running on port 3306. You can check this post to figure out which port is your mysql DB running on. https://serverfault.com/questions/116100/how-to-check-what-port-mysql-is-running-on. Below is a reference for you. Please see the comments.
// create connection to DB
const connection = mysql.createConnection({
host: "localhost",
user: 'root',
password: 'root',
port: 3000 // You need to change this and put in the correct port number.
});

How to connect to a database on a remote server

I have a server, my-website.com, on a shared hodting plan. I created a database on the server. From the webadmin, the db details are :
From phpMyAdmin :
Server: localhost:3306
Database server
Server: Localhost via UNIX socket
Server type: Percona Server
Server version: 5.6.39-83.1 - Percona Server (GPL), Release 83.1, Revision da5a1c2923f
Protocol version: 10
User: user#localhost
Server charset: UTF-8 Unicode (utf8)
I try to connect to it via node :
const express = require('express')
const mysql = require('mysql')
const PORT = process.env.PORT || 5000
const app = express();
app.use(express.json());
const courses = [];
/** DB **/
app.get('/api/db_connect', function (req, res) {
var myConStatus = "undef conn";
var con = mysql.createConnection({
host: "191.181.181.81", // FAKE
Port: "3306",
user: "user#localhost",
database: "user_test_db",
password: "password123"
});
con.connect(function (err) {
myConStatus = "Connecting to db";
if (err) {
myConStatus = "ERR Conn";
throw err;
}
myConStatus = "Success Connection";
});
var sql = "CREATE TABLE customers (name VARCHAR(255), address VARCHAR(255))";
con.query(sql, function (err, result) {
myConStatus = "Creating table";
if (err) {
myConStatus = "ERR DB TABLE CREATE";
throw err;
}
myConStatus = "Table created";
});
res.send(myConStatus);
});
/** END DB **/
This is never successful and no table gets created.
What am I missing?
Not sure if I understand fully, but mySQL can be configured for connections from local processes or from remote. If you are trying to connect remotely to a server that is configured for local it will not connect.
You did not say if you got connections errors or not.
You can configure connections for standard TCP/IP or ssh TCP/IP as opposed to local socket/pipe - which maybe you have done.
See here https://www.percona.com/doc/percona-xtrabackup/LATEST/howtos/enabling_tcp.html and this quote
"Most of the Linux distributions do not enable by default to accept
TCP/IP connections from outside in their MySQL or Percona Server
packages"
If this is off the mark - just comment me and I will delete.

Error connecting to MySQL from Node-JS server

I am learning to develop server on node-js and have developed a basic get function which retrieves data from MySQL DB hosted on a ubuntu server at digitalocean.
Here's my code:
const express = require('express')
const app = express()
const mysql = require('mysql')
const Client = require('ssh2').Client;
const ssh = new Client();
const db = new Promise(function(resolve, reject){
ssh.on('ready', function() {
ssh.forwardOut(
// source address, this can usually be any valid address
'localhost',
// source port, this can be any valid port number
3333,
// destination address (localhost here refers to the SSH server)
'xxx.xxx.xxx.xxx',
// destination port
22,
function (err, stream) {
if (err) throw err; // SSH error: can also send error in promise ex.
reject(err)
// use `sql` connection as usual
connection = mysql.createConnection({
host : '127.0.0.1',
user : 'user',
password : 'pass',
database: 'mysql',
stream: stream
});
// send connection back in variable depending on success or not
connection.connect(function(err){
if (!err) {
resolve(connection)
} else {
reject(err)
}
});
});
}).connect({
host: 'xxx.xxx.xxx.xxx', //IP address where DB is hosted
port: 22, //Port refering to the IP
username: 'user', //username to loginto the host
password: 'pass' //password to log into host
});
});
//Retrieve route
app.get('/users', (req, res) => {
//console.log("Fetching user with id: " + req.params.id)
const queryString = "SELECT * FROM user"
connection.query(queryString, (err, rows, fields) => {
if(err){
console.log("Failed to query " + err)
res.sendStatus(500)
return
}
console.log("Fetch Succesful")
res.json(rows)
})
})
app.listen(3000, () => {
console.log("Server is up and listerning on port 3000")
})
When I run this code on my local machine it is able to connect to external DB and fetch the data. I have created another server at digitalocean and hosted the same code. However upon running it I get error at connection stating: UnhandledPromiseRejectionWarning: Error: connect ECONNREFUSED 127.0.0.1:3306
I tried various solutions available on the platform but could not suceed.
I have written the code accoring to the documentation but still clueless what's causing the error.
Thank You.