Connect Express js project to external MySQL databse via SSH - mysql

I would like to know the best way to connect an Express.js project to an external MySql database using conf.ini ?
Should I use SSH ?

There is no need for ssh, mysql has it's own protocol to connect remote servers, you only need to use mysql module for nodejs, the following code is to ensure connection between hosts:
const mysql = require('mysql');
var connection = mysql.createConnection({
host : 'remote_ip',
user : 'mysql_username',
password : 'password',
database : 'database_name'
});
connection.connect( function (err) {
if (err) {
console.log('Cannot connect to mysql server', err);
} else {
console.log('Successfully connected');
}
connection.end();
});
One last thing, make sure to edit mysql config file /etc/mysql/my.cnf and set bind-address parameter to 0.0.0.0, and do not forget to restart mysql service: sudo service mysql restart

Related

(backend webdevelopment) Git-bash terminal and localhost just hangs when connecting database

Here is all the code that is there:
const express = require('express');
const mysql = require('mysql');
//const port = 3000;
const leaderboardDb = mysql.createConnection({
//host : 'localhost',
host: '127.0.0.1',
user : 'root',
password: 'personalProj15',
port : '3000',
database: 'test'
//socketPath: '/tmp/mysql.sock'
})
leaderboardDb.connect((err) => {
if(err) {
console.log(err);
}
else {
console.log('MySQL connected');
}
})
const app = express();
app.listen('3000', () => {
console.log('Server started (on 3000)');
})
app.get('/createDb', (request, response) => {
let sql = 'CREATE DATABASE leaderboardDatabase';
leaderboardDb.query(sql, (err, result) => {
if(err) { throw err}
else {
console.log(result);
response.send("Testing...");
}
})
})
"Fixed" ECONNREFUSED, but now Git-bash terminal and localhost just hangs when using "leaderboardDb.connect((err)". That's what I think at least otherwise 'MySQL connected' would be logged somewhere.
Notes:
The error is being thrown from leaderboardDb.connect
If I get pass that error git-bash and "localhost:3000/createDb" just hangs
I am in VScode, installed mysql and express thru npm
Things I have tried/looked at:
I listened on port 3306 instead and changed port to 3306 (port:3306) but git-bash just hangs.
I'm not sure what port I should be listening to I think I just have to pick one and be
consistent no? (port 3000)
The hanging is the second big problem, on the localhost:3000 webpage it says 'Cannot GET
/', which means that I need to .connect, right? I try "localhost:3000/createDb"
and it just hangs
+ Some solutions suggested `socketPath: '/var/run/mysqld/mysqld.sock'` and a different path that involved `/tmp/mysql.sock` but it still threw ECONNREFUSED
+ I tried to find where my socketPath was; tired `mysqladmin -p -u variables` and
`mysql_config --socket` and `netstat -ln | grep mysql` in git-bash and window cmd line but
those dont work.
+ Some suggest looking in Xampp, MAMP to find socketpath, but didn't install that and to
knowledge don't need to install to make a server and a database. Can't I just find the
socket path in windows cmd line/git-bash?
Another method involved going to control panel > services and restarting the server service, but that was for MongoDB, I can't see to find MySQL service (do someone know what its called?)
Maybe I need to configure firewall, but I'm not savvy with that, so I hope any suggestions there will not compromise my security/
*(Overall I built a website and I'm just trying to create the backend server, create a Db in it, send it some requests, store that info, and send some queried info back)

MySQL connection node

I'm running my node app on a linux vps where I have installed apache2 and phpmyadmin. I have my mysql database on the server there which I can connect to user the mysql -uusername -ppassword command, but when running my node app with this code:
const mysql = require('mysql');
const connection = mysql.createConnection({
host : '127.0.0.1',
user : 'root',
password : '*******',
database : 'db_name',
});
connection.connect(function(e) {
if(e) {
console.log('Database didn\'t connect');
} else {
console.log('Database connected successfully');
}
});
It says "database didn't connect". the user, password and db fields are all correct for sure.
When console.log(e) I'm getting:
I'm getting:
error code: 'ER_NOT_SUPPORTED_AUTH_MODE'
errorno: 1251
sqlMessage: 'Client does not support authentication protocol requested by server; consider upgrading MySQL client'.
anybody knows why ?
You can change the connection to use the unix socket or check the mysqld is binding on 0.0.0.0 or on the ip of the ethernet card of the server it's running on.
According to the mysqld version you're using, the option can be "skip-networking" or "bind-address".

How to connect mysql database with nodejs from google cloud

I have a NodeJs application and MySQL database.
I have deployed nodejs application in google cloud and created MySQL database in google cloud and connected to nodejs application
i am able deploye the application successfully but application not able to connect to cloud mysql dayabase.
But when i am trying to connect cloud mysql from my local mysql workbench, it's successfully connecting to database. and i am able to connect cloud mysql database from local nodejs application
but i am not able to connect from deployed nodejs application to cloud mysql db
error Database is not connectedError: connect ETIMEDOUT
Db.js
var mysql = require('mysql');
var PropertiesReader = require('properties-reader');
var properties = PropertiesReader('./db.properties');
var connection = mysql.createConnection({
connectionLimit : properties.get('pool'),
host: properties.get('hostname'),
user: properties.get('username'),
password: properties.get('password'),
database: properties.get('dbname')
});
connection.connect(function (err) {
if (!err) {
console.log("Database is connected");
} else {
console.log("Database is not connected" + err);
}
}
);
module.exports = connection;
app.yaml
runtime: nodejs
env: flex
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. Socket path must be something like this
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

initiating sequelizer mysql connection via tunnel-ssh module

I'd like to connect to a MySQL database using Sequelizer. Right now, I'm getting a Connection Refused Error.
To access the database, I have to SSH in. According to Mick Hansen here: https://github.com/sequelize/sequelize/issues/3753, one way to SSH in is to use tunnel-ssh to establish the tunnel, then initiate Sequelizer.
My (unsuccessful) approach so far has been to initiate the tunnel, then when the tunnel opens, test whether Sequelizer has authenticated.
Update
Host: DigitalOcean
CLI Success: I can 1) ssh into digitalocean server 2) login into mysql from the server and 3) access all database information as the root user.
Sequel Pro: I can also log into the database using Sequel Pro.
MySQL 127.0.0.1:3306: Based on the mysql/my.cnf file, the port is 3306 and the bind-address is 127.0.0.1. The config file also says instead of skip-networking, the default is to listen only on localhost, if that's relevant.
socketPath -> Error Connection Switching from TCP to socket seems to sometimes work for this type of problem, but when I tried it, I continued to get a connection refused error.
2 Error Types - "All Configured Authentication Methods Failed" and "Error Connection Refused"
Thanks for the help!
Code:
// sequelize config
var sequelize = new Sequelize('database', 'user', 'pass', {
host: '127.0.0.1',
dialect: 'mysql',
port: 3306,
pool: {
max: 10,
min: 0,
idle: 20000
}
});
// tunnel config
var config = {
user:'user',
host:'sshHost',
port:22,
dstHost:'127.0.0.1',
dstPort:3306,
srcHost:'127.0.0.1',
srcPort:3306,
localHost:'127.0.0.1',
localPort: 3306,
privateKey:require('fs').readFileSync('/path/to/key')
};
var tunnel = require('tunnel-ssh');
// initiate tunnel
tunnel(config, function (error, server) {
//....
if(error) {
console.error(error);
} else {
console.log('server:', server);
// test sequelize connection
sequelize
.authenticate()
.then(function(err) {
console.log('Connection established');
})
.catch(function(err) {
console.error('unable to establish connection', err);
})
}
})
When my config is set to the object above, I get an "All configuration methods failed error".
If I change my config to the below, I get a "Sequelize Error Connection Refused" error.
// tunnel config
var config = {
user:'user',
host:'sshHost',
port:22,
dstHost:'127.0.0.1',
dstPort:3306,
//srcHost:'127.0.0.1',
//srcPort:3306,
//localHost:'127.0.0.1',
//localPort: 3306,
privateKey:require('fs').readFileSync('/path/to/key')
};
localPort is the port listening on your local system. Currently you have it defined as 27000 but your Sequelize config is set to 3306.

Can't connect to localhost database from node.js server

Been having a lot of trouble trying to connect to to my localhost database. I've tried using the mysql and mysql-simple node modules but in both cases I just can't get it to connect.
Here's what I used with the 'mysql' module:
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
port : '8000',
user : 'uber',
password : 'pass',
});
connection.connect(function(err) {
if (err) throw err;
console.log('Connection Successful');
});
connection.query('USE someDB', function(err) {
if (err) throw err;
console.log('Query Successful');
});
And here' what I used with the 'mysql-simple' module:
var database = require('mysql-simple');
database.init('uber', 'pass', 'mysql', 'localhost', 8000);
database.querySingle('SELECT Host FROM user', function(err, results) {
if (err) {
console.log('error fetching some active users: ' + err);
return;
}
log('Query Successful');
for (var i = 0; i < results.length; i++)
console.log('got active user ' + results[i]);
}
In both cases, when I run my node.js server, it never logs that its connected. I've tried replacing localhost with '127.0.01' and creating a new user to make sure the password is correct, but to no avail. Why isn't it connecting?
Thanks
It's most likely that networking is turned off, that means that mysql server communicates with clients via UNIX sockets and not via TCP/IP. You can check that out running mysql client and run "status" command. If you see port number there, then your mysql server communicates via TCP/IP, or else you'll see something like "socket pathname…", get the pathname and give it to node.js connection parameters, e.g.
...
socketPath: '/opt/lampp/var/...',
...
Check that out in https://github.com/felixge/node-mysql page (search for "socketPathname")
Hope, that's your problem.
You should use mysql_config to show the path to socket.
This a sample on my MAC
QuyLes-MacBook-Pro:freelancer quyle$ mysql_config
Usage: /Applications/MAMP/Library/bin/mysql_config [OPTIONS]
Options:
--cflags [-I/Applications/MAMP/Library/include -fno-omit-frame-pointer -g -DNDEBUG]
--include [-I/Applications/MAMP/Library/include]
--libs [-L/Applications/MAMP/Library/lib -lmysqlclient -lz]
--libs_r [-L/Applications/MAMP/Library/lib -lmysqlclient_r -lz]
--plugindir [/Applications/MAMP/Library/lib/plugin]
--socket [/Applications/MAMP/tmp/mysql/mysql.sock]
--port [0]
--version [5.5.42]
--libmysqld-libs [-L/Applications/MAMP/Library/lib -lmysqld]
--variable=VAR VAR is one of:
pkgincludedir [/Applications/MAMP/Library/include]
pkglibdir [/Applications/MAMP/Library/lib]
plugindir [/Applications/MAMP/Library/lib/plugin]
and then, you add key socketPath for yourMysqlConnection.
bellow on my sample
MysqlServer: {
adapter: 'sails-mysql',
host: 'localhost',
user: 'root', //optional
password: 'root', //optional
database: 'nodejs', //optional,
socketPath: '/Applications/MAMP/tmp/mysql/mysql.sock'
},
change this
database.init('uber', 'pass', 'mysql', 'localhost', 8000);
to
database.init('uber', 'pass', 'mysql', 'localhost', 3306);
and you should be through
Make sure that MySQL and express are running on the same port.
I had MySQL bundled from XAMPP, that ran on Port 3036.
On setting app.listen to 3036, my code worked. FINALLY!
Try this code it's work for me
var mysql = require('mysql');
var connection = mysql.createConnection(
{
host : 'localhost',
user : 'root',
password : '',
database : 'urdatabase',
}
);
connection.connect();
query = connection.query("SELECT * FROM UrTable;");
query
.on('error', function(err) {
console.log( err );
})
.on('result', function( data ) {
socket.emit('YourData',data);
});
I hope this will be helpful for you
In my case, anything happened, so I solved by generating new GRANTs with a new user for nodejs apps
Its due to the networking is turned off in MySQL configurations.
In Ubuntu 20.04.2 and MySQL 8.x.x(its worked in my case) you can find this settings in
/etc/systemd/system/mysql.service.d/override.conf
there will be a ExecStart key and its have multiple configurations.
Here you can provide --skip-networking as OFF
--skip-networking=OFF
And you have to restart your service
systemctl restart mysql.service
It will allow you to connect localhost