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
Related
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)
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
I have a problem when I try to connect to a MySQL database hosted by OVH on NodeJS server. Here is the code :
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'my_ip',
port : '3306',
user : 'my_user',
password : 'my_pass',
connectTimeout : 10000
});
connection.connect(function(err) {
if (err) {
console.error('error connecting: ' + err.stack);
return;
}
console.log('connected');
});
But I get :
error connecting: Error: connect ETIMEDOUT
Everytime, not matter what I do, like changing the timeout, remove the port or anything else. Any idea ? I'm running this on ArchLinux x86_64
I finally found the answer : OVH doesn't allow customers to use their MySQL Database out of their services which means that if you want to run code using MySQL OVH database, you have to run the code into a OVH server.
This looks like a timeout error.
Please try taking the port number out of the quote marks. Hopefully this will fix the issue!
var connection = mysql.createConnection({
host : 'my_ip',
port : 3306,
user : 'my_user',
password : 'my_pass',
connectTimeout : 10000
});
I have a node.js server that works but needs to be set up for ssh connections:
var mysql = require('mysql')
var io = require('socket.io').listen(3000)
var db = mysql.createConnection({
host: 'hostname',
user: 'username',
password: '12345',
database: '12345',
port: 3306,
socket: '/var/run/mysqld/mysqld.sock'
})
db.connect(function(err){
if (err) console.log(err)
})
I'm aware that there are ssh npm libraries for this purpose, however the options available (ssh2, node-sshclient, etc) appear to deal with pretty intricate features that may overcomplicate things. I'm looking for the simplest way to connect to my mysql db through ssh. What would be the best way to accomplish this?
If you are running a linux/unix system do the following:
Connect to your mysql server via ssh and proxy the mysql port (default is 3306) via this ssh tunnel.
This works as follows:
1 Type in screen (to start a screen session which is permanent even if the shell gets closed).
2 Type into screen shell:
ssh -L 3306:127.0.0.1:3306 your_servers_domain_or_ip -lyour_login_name
3 Enter your ssh password / or use a PKI auth to avoid manual steps
4 Done... now it’s possible to connect MySQL like you would do when it’s installed on the same machine as your application.
Connect to MySQL from node.js like below:
var db = mysql.createConnection({
host: '127.0.0.1', // Important to connect to localhost after connecting via ssh in screen
user: 'username',
password: '12345',
database: '12345',
port: 3306
});
Sometimes it's preferrable to instantiate the SSH tunnel connection dynamically (in code) rather than separately using OS libraries. For example, it makes it easier to automatically close the connection, share the environment with other developers, or conditionally use an SSH tunnel depending on the environment.
With packages such as tunnel-ssh, this is easy. Building on the example provided, the connection code would look like:
import { createSSHTunnel } from "./sshTunnel";
const { srcAddr, srcPort } = await createSSHTunnel();
var db = mysql.createConnection({
host: srcAddr,
port: srcPort,
user: 'username',
password: '12345',
database: '12345'
});
With all logic cleanly abstracted away in the sshTunnel module, that could look like:
// sshTunnel.js
import { createTunnel } from "tunnel-ssh";
export async function createSSHTunnel(srcAddr = "127.0.0.1", srcPort = 12345) {
const tunnelOptions = {
autoClose: true,
};
const serverOptions = {
port: srcPort,
};
const sshOptions = {
host: process.env.SSH_HOST,
port: parseInt(process.env.SSH_PORT),
username: process.env.SSH_TUNNEL_USER,
password: process.env.SSH_TUNNEL_PASSWORD,
};
const forwardOptions = {
srcAddr: srcAddr,
srcPort: srcPort,
dstAddr: process.env.DB_HOST,
dstPort: parseInt(process.env.DB_PORT),
};
try {
await createTunnel(
tunnelOptions,
serverOptions,
sshOptions,
forwardOptions
);
} catch (error) {
if (error.code === "EADDRINUSE") {
// Assume port is uniquely used by SSH tunnel, so existing connection can be reused
console.log(`Returning existing SSH tunnel on ${srcAddr}:${srcPort}.`);
return { srcAddr, srcPort };
} else {
throw error;
}
}
console.log(`SSH tunnel successfully created on ${srcAddr}:${srcPort}.`);
return { srcAddr, srcPort };
}
Remarks:
The SSH tunnel arbitrarily uses local port 12345
The environment variables involved are:
DB_HOST: the database hostname
DB_PORT: the database port, 3306 in the original MySQL example, 5432 for Postgres etc.
SSH_HOST: the hostname of the machine serving the SSH tunnel
SSH_PORT: the port of the machine serving the SSH tunnel
SSH_TUNNEL_USER: the username for the SSH tunnel
SSH_TUNNEL_PASSWORD: the password for the SSH tunnel
I am just getting started with nodejs.
My question is that i get an Error:
connect ECONNREFUSED
npm install mysql;
server.js
var mysql = require('mysql');
var connection = mysql.createConnection({
host: '127.0.0.1',
port: '3306'
});
connection.connect(function(err) {
if(err) {
console.log(err);
}
});
connection.end();
Finally
1.I don't know the "user" and "password";
2."In mysql.conf, comment skip-networking.", I can't find mysql.conf;
3.I have tried this and it's not working, my platform is windows 7.
var client = mysql.createClient({
user: uuuu,
password: pppp,
host: '127.0.0.1',
port: '3306',
_socket: '/var/run/mysqld/mysqld.sock',});
It's clear you have not install mysql server in your windows yet. So you should go to http://www.mysql.com and download the server, install and set up, you can set your username and password and grant privilege to it, so you will know the user and password, and mysql.conf will be inside your installation. And if you are in windows, generally you would not use a UNIX socket to build the connection. So "_socket: '/var/run/mysqld/mysqld.sock'" should not be here.