Node.js MySQL - Error: connect ECONNREFUSED - mysql

I use Node.js server side. I tried my code on localhost and everything works fine. I bought a server and installed Apache and node.js on it and test my web application there. I correctly changed the MySQL connection configurations from localhost to the server configurations.
I test my web application with this configuration:
var mysql = require('mysql');
var mysqlConnection;
function new_mysqlConnection() {
mysqlConnection = mysql.createConnection({
host : 'myurl.at',
user : 'myusername',
database : 'mydatabase',
password : 'mypassword'
});
}
I start the node.js server with:
$ node server.js
When I load the page, it's correctly displayed, but when Node.js try to connect to the database I always got the following error:
Error: connect ECONNREFUSED
at errnoException (net.js:905:11)
at Object.afterConnect [as oncomplete] (net.js:896:19)
--------------------
at Protocol._enqueue (/var/www/node_modules/mysql/lib/protocol/Protocol.js:135:48)
at Protocol.handshake (/var/www/node_modules/mysql/lib/protocol/Protocol.js:52:41)
at Connection.connect (/var/www/node_modules/mysql/lib/Connection.js:119:18)
at reconnectDb (/var/www/server.js:319:18)
at app.get.email (/var/www/server.js:109:2)
at Layer.handle [as handle_request] (/var/www/node_modules/express/lib/router/layer.js:82:5)
at trim_prefix (/var/www/node_modules/express/lib/router/index.js:302:13)
at /var/www/node_modules/express/lib/router/index.js:270:7
at Function.proto.process_params (/var/www/node_modules/express/lib/router/index.js:321:12)
at next (/var/www/node_modules/express/lib/router/index.js:261:10)

You need to add the value of socket path to the config object:
socketPath: '/var/run/mysqld/mysqld.sock'
In MAMP, you go to http://localhost:8888/MAMP, and you find:
/Applications/MAMP/tmp/mysql/mysql.sock
At the end you have:
var connection = mysql.createConnection({
host : config.host,
user : config.user,
password : config.pass,
database : config.db,
socketPath: '/Applications/MAMP/tmp/mysql/mysql.sock'
});

I was having same problem but I solved this by changed
host: 'localhost'
to
host: '127.0.0.1'

Check for your MySQL port in your server.
In MAMP, by default it uses 8889.
Add that to your connection config.
Your MySQL config should look like this.
this.pool = mysql.createPool({
connectionLimit: 10,
host: 'localhost',
user: 'root',
password: 'root',
database: 'todo',
port: '8889'
});

Check your xampp server mysql is running or not

I fix it by the following code after a struggle of two days. ( Just giving my solution, you might have another solution as well.)
Follow these steps as well.
Delete all node_modules
Run "npm audit --force"
install npm packages by "npm install"
const sequelize = new Sequelize("test", "root", "root", {
host: "127.0.0.1",
dialect: "mysql",
port: "8889",
connectionLimit: 10,
socketPath: "/Applications/MAMP/tmp/mysql/mysql.sock"
});
Note: I am using sequelize with graphql (NODEJS).

if using using express and MySQL. port should be same as your MySQL port.
The default MySQL port is 3306.
let defaultPORT = 3306;
var express = require('express');
var app = express();
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user : 'yourMYSQLUser',
password : 'yourMYSQLPassword'
});
connection.connect();
connection.query('SELECT 1 + 1 AS solution', function (error, results, fields) {
if (error) throw error;
console.log('The solution is: ', results[0].solution);
});
var server = app.listen( defaultPORT, function() {
console.log( defaultPORT)
});

I would recommend to add the port in the below table of yours;
const pool=mysql.createPool({
host: '127.0.0.1',
user: 'root',
database: 'node-complete',
port: "3307",
password: 'Aditya2000#'
});
The port number is to be taken from your MySql Workbench from the homepage table of it which should shows:
Local Instance MySql root localhost: 3307 -> this localhost number
has to be written there.

In most cases, your host should match your bind-address in the MySQL config file.
if your bind-address is 0.0.0.0 or 127.0.0.1 then setting host to 'localhost' should work. but if your bind-address is your actual IP address then you should add your IP address instead.
var sql_con = mysql.createConnection({
host: "ip address",// should be the same as bind-address
user: "jeffery",
password: "damnthing",
database: "KOKATOOO"
});

I had the same issue turns out mysql was not running.
Make sure it's running by:
$ systemctl status mysqld
If you see this:
● mysqld.service - MySQL Server
Loaded: loaded (/usr/lib/systemd/system/mysqld.service; enabled; vendor preset: disabled)
Active: failed (Result: start-limit) since Tue 2020-08-18 12:12:29 CDT; 32min ago
Docs: man:mysqld(8)
http://dev.mysql.com/doc/refman/en/using-systemd.html
Process: 18668 ExecStart=/usr/sbin/mysqld $MYSQLD_OPTS (code=exited, status=2)
Process: 18650 ExecStartPre=/usr/bin/mysqld_pre_systemd (code=exited, status=0/SUCCESS)
Main PID: 18668 (code=exited, status=2)
Status: "SERVER_BOOTING"
Then the service is not running, to run enter:
$ systemctl start mysqld

I Also have same problem in google cloud with nginx
changed
host: 'localhost'
to
host : 'cloud_instance_private_ip'
may help some one with same problem

It's probably course from the absence of port and database.
first I wrote:
host,
user,
password and no database and port.
Here you need to specified what is your database name, what is your port number.
So the total must be:
1. host
2. user
3. password
4. database
5. port
It's works for me, try it if it works for you too.

I 'm also have same problem but i found the solution by adding:
port:"80"
I connect with node.js to the server php mysql using this code:
var mysql=require('mysql');`
var connection=mysql.createConnection({
port:"80",
host:"localhost",
user:"root",
password:""
});

open services from the search bar.In there search for MySQL80.Right click on it and click on start.Now run the code.It should work.Most of the times the SQL service is inactive when the computer starts up

have experienced a similar issue where with the same configs, could connect from local -> mysql server but not when deployed as cronjob to k8s cluster. Not sure why but workaround was to add sleep 10 && before running application: args: ["-c", 'sleep 10 && node index.js']

I had same issues, and i resolved it by adding my port
Port: YOUR_PORT
had this same issue and I solved it by adding the port

I created a new user in PhpMyAdmin with a username as "user" and password as "". I set the host as "%" which allows connection from any host.
Use the IP address you find in the XAMPP control panel as the host in the node js code
I have used the IP address in the XAMPP control panel as the host in the database connection
This solved the problem and connected to the database

Maybe it will help someone, In my case I am using strapi app when I encountered this issue, I realized that I did not create database, So I am using Mamp I go to php my admin created db and updated database.js in config folder and now its working fine

In my case it was working locally, but now when deployed.
The problem was I hadn't updated the environment variables

I am facing the same problem but I have done that:
Turn ON your MySQL using XAMPP
Create a database that will mention in the code. (I have 'node js' named database.
By doing these, my code is worked perfectly.
You can see here

Related

NodeJS xdevapi - Creating Connection to MySQL Database

I've been using the official MySQL NPM package found here: https://www.npmjs.com/package/#mysql/xdevapi.
However, I can't seem to make a connection to the server. Here's the current error message I get:
Error: The server connection is not using the X Protocol.
Make sure you are connecting to the correct port and using a MySQL 5.7.12 (or higher) server intance.
Here is the code that generates that issue:
const db = mysqlx.getSession('root#localhost:33060/schemaname').then(session => {
console.log('SESSION STARTED!!');
});
This is just a test database without a password so I don't think the password is the issue. Also, I've made sure I'm using the right port and the MySQL version is 8.x.x so I don't think that is the issue. I created a database using the app Dbngin and I verified I could connect to the database by running the following command in my terminal: mysql -u root -h 127.0.0.1 --port=33060 -p which worked. I'm also running this on my Mac.
Update:
I've also tried passing a config object without much luck:
const config = {
user: 'root',
password: '',
host: 'localhost',
port: 33060,
schema: 'schemaname'
};
const db = mysqlx.getSession(config).then(session => {
console.log('SESSION STARTED!!');
});
Unfortunately, this code produces the same error above.
I tried it out myself and got the same error because you are using the wrong port. It could be you changed the default port, but the default port is: 3306 and not 33060 although I have to use port 33060 while my port is 3306.
X-protocal requires you to multiply your port by 10 I see here: https://dev.mysql.com/doc/mysql-port-reference/en/mysql-ports-reference-tables.html. So if your original port is 33060 I guess it should be 330600.
You could try this command SHOW VARIABLES LIKE 'mysqlx_port';

errorError: getaddrinfo ENOTFOUND - mysql

I'm running a server on c9.io using Node.js and trying to connect to Mysql
I guess I get this error:
Error: getaddrinfo ENOTFOUND
because the connection to the db is wrong.
I'm using this:
var connection = mysql.createConnection({
host: "REMOTE_ADDR",
user: "MYUSERNAME", // this is replaced by my username
database: "c9",
port: 3306
});
Any idea what's wrong?
Thanks!
After one hour, and I don't know why, I found the issue.
In my case I replaced
host: 'localhost'
by
host: '127.0.0.1'
I know it's been a while since this was asked but I spent the better part of today trying to fix this. What to check for:
Within your nodejs source:
Try it without the 'port' option unless on your db VM, MySQL is
listening on a port besides 3306. I had this option specified but had
connection problems until I removed it. And 3306 is already the
default value for the option anyway.
Try it with the actual host IP in the host 'option'. I was using an actual domain name and, more often than not, node-mysql would throw
the same exact "errorError: getaddrinfo ENOTFOUND" When I used the IP
address, no more errors. Also, I did not get this error while on
Ubuntu instances in AWS. As soon as I switched over to Ubuntu VMs in
Azure, I got the problem.
Set the "debug" connection option to true which will give you a verbose trace of what's happening during the connection
On your db VM/Box/Instance:
Ensure that MySQL is listening on the right port
If you're seeing the error when trying to make concurrent connections using a pool, check that your max_connections and max_user_connections haven't been changed from the default settings in my.conf
Monitor "SHOW PROCESSLIST;" in MySQL to see if you see any issues there
This code works for me.
var mysql = require('mysql');
var con = mysql.createConnection({
host: '127.0.0.1',
port: '3306',
user: 'yourUsername',
password: '**********'
});
con.connect(function(err){
if(err) throw err;
console.log('connected!');
});
the host and port name find them in your mysql server.
in-place of '127.0.0.1' you can use 'localhost'
I was facing this issue. I did fix it simply you have to change your configuration of a connection string like if you are running on local machine try
host:'localhost' or host:'127.0.0.1'
...and set your user name and if you want this to publish your code on server then give the host according to server if in docker container give it name host:'db'.
I almost spend two hours to understand what is the problem with the mysql database. I am using Windows cmd.
I tried multiple ways e.g
npm install mysql2
Changing localhost to 127.0.0.1
Refreshing node
so in order to resolve this issue
[Error: getaddrinfo ENOTFOUND 127.0.0.1:3306]
I open XAMPP and start the MySQL database then manually check the credentials and works fine for me.
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user : 'test',
password: 'test123',
});

node-mysql error: connect ECONNREFUSED

I'm trying to setup a remote connection between my database server and a client node app using node-mysql.
When I try to connect to the remote db, I get this error:
node.js:201
throw e; // process.nextTick error, or 'error' event on first tick
^
Error: connect ECONNREFUSED
at errnoException (net.js:646:11)
at Object.afterConnect [as oncomplete] (net.js:637:18)
Connecting to a local db works ok (with the socketPort parameter).
I can connect to this remote db with PHP from my computer localhost as well as another server I own so I don't think there's something wrong with mysql conf.
For info, nodejs is running with nginx and I've setup a proxy to make node work on port 80, maybe this is the issue?
How can I check that?
Thanks.
EDIT
Here's my code, just in case:
var express = require('express');
var mysql = require('mysql');
var app = express();
var connection = mysql.createConnection({
debug: false,
host: '12.34.56.67',
user: 'user',
password: 'pass'
});
Try using mysql socket:
var connection = mysql.createConnection({
user: 'user',
password: 'pass',
socketPath: 'mysql-socket-path', /*example: /Applications/MAMP/tmp/mysql/mysql.sock*/
database: 'dbname'
});
Should one still look for an answer:
Check your MySql server's configuration.
In my case running netstat -ln | grep mysql(as per Troubleshooting Problems Connecting to MySQL) revealed that my server is listening on the socket /tmp/mysql.sock so in createConnection's options I used socketPath: '/tmp/mysql.sock' instead of host: and port:
This error has to do with the MySQL client not being able to connect to the host:port given. As defined in errno.h, ECONNREFUSED is an error that is thrown when a connection is refused - this is possibly caused by:
a firewall such as iptables blocking the port
no such process running on the port
the process is running on a different host
the host or port were incorrect
In my case, my MySQL server was not correctly bound to 0.0.0.0 for external connections, instead being bound to 127.0.0.1, as it is by default; however you can change this.
The error does not originate from the node-mysql package, as doubly shown by the stacktrace, which only shows errors from net.js.
I added port:3306, that solved the issue .
var connection = mysql.createConnection
({
user: 'root',
password: 'root',
server: 'localhost',
port:3306,
database: 'abcd',
insecureAuth: true,
dialect: 'mysql',
multipleStatements: true,
pool: {
max: 5,
min: 0,
acquire: 30000,
idle: 10000
}
});
connection.connect();
Ok so I checked with node-mysql dev and it seems that it's not a node-mysql bug, but it was hard to investigate more.
Anyway, I found this lib which works, so I'll go with it.
https://github.com/mariano/node-db-mysql
i had the same problem.
solved it, by set the right port in the createConnection function options.
get your port by using following command:
netstat -tlnp
search for program name mysqld or just named.
Use the command: yarn run start, and DO NOT use: cd /folderX && yarn run start

node.js mysql error: ECONNREFUSED

Why can't I connect to the mysql server?
On the same server an Apache/PHP server is running and it connects without problems!?
var mysql_link = {
host : 'localhost',
port : 3308,
database: 'nodetest',
user : 'root',
password : 'xxx'
};
var connection = mysql.createConnection(mysql_link);
connection.connect(function(err){
console.log(err);
if(err != null){
response.write('Error connecting to mysql:' + err+'\n');
}
});
connection.end();
error
{ [Error: connect ECONNREFUSED]
code: 'ECONNREFUSED',
errno: 'ECONNREFUSED',
syscall: 'connect',
fatal: true }
update
root#dyntest-amd-6000-8gb /var/www/node/dyntest # ps ax | grep mysqld
7928 pts/0 S+ 0:00 grep mysqld
28942 ? S 0:00 /bin/sh /usr/local/mysql/bin/mysqld_safe --datadir=/var/lib/mysql --pid-file=/var/run/mysqld/mysqld.pid
29800 ? Sl 17:31 /usr/local/mysql/bin/mysqld --basedir=/usr/local/mysql --datadir=/var/lib/mysql --plugin-dir=/usr/local/mysql/lib/plugin --user=mysql --log-error=/var/lib/mysql/mysql-error.log --open-files-limit=65535 --pid-file=/var/run/mysqld/mysqld.pid --socket=/var/run/mysqld/mysqld.sock --port=3306
I know this question has been answered, but for me the problem was that the mysql server listens on a Unix socket not on a tcp socket. So the solution was to add:
port: '/var/run/mysqld/mysqld.sock'
to the connection options.
If this has worked before, my first guess would be that you've already got a copy of your node.js script running in the background which is holding the connection.
I believe connection refused is a tcp/ip error message, rather than something from MySQL which suggests that it is either not running or is running on another port or with sockets.
Could you try telnet'ing to port 3308? To see if the server is running on that port?
telnet localhost 3308
Can you also try:
mysql -hlocalhost -uroot -pxxx
Overview
For anyone else having this problem and is running mamp. I suspected the problem had to do with the network and not MySQL or Node.js.
Solution
If you open MAMP and click MySQL in the left navigation panel it will pull up the MySQL options page. In the center of the page you will see a checkbox that says,
"Allow network access to MySQL".
Check this box and then restart your MAMP. At this point you can now test your connection to MySQL with telnet or a node.js script.
Hint
Remember you can check which port your MySQL is running on by opening MAMP and clicking the ports link on the left navigation panel.
Visual Aid
For some very odd reason, my computer only allowed me to have port 3306 as default port for my connection in order for it to work.
Mac OS on M1 MacBook Pro here with MySQL installation via brew:
Changing the host from 'localhost' to '127.0.0.1' and creating a different user with a password solved this issue for me.
For some reason I cannot connect to my DB with root user and no password.
I created the new user on MySQL Workbench, but you can create a new user with admin privileges via the mysql CLI also.
Just google it.
This is how my backend looks:
const express = require('express');
const mysql = require('mysql');
const app = express();
const port = 3500;
const db = mysql.createConnection({
host: '127.0.0.1',
user: 'admin',
password: 'admin',
});
db.connect((err) => {
if (err) throw err;
console.log('connected to database');
});
app.listen(port, () => {
console.log('server listening on port 3500');
});
I wanted to comment my solution here, just in case there were people as newbie as me in databases.
I was getting this error because I had installed the mysql NPM package correctly but I hadn't installed any implementation of MySQL on my computer (I didn't know I had to).
I'm using Arch Linux so, in my case, with the NPM package already installed in my project, I did pacman -Syu mariadb (MariaDB is the default implementation of MySQL in Arch Linux) and then configured it following the guide.
Then, you can use the root user you just configured or create a new one to use in your project. For the latter:
Enter mysql CLI by running mysql -u root -p.
Enter the password for root user.
Create a new database with CREATE DATABASE mydatabase;.
Create a new user with CREATE USER test IDENTIFIED BY "testpass";.
Grant privileges to test user to use your new database with GRANT ALL PRIVILEGES ON mydatabase.* TO test#localhost IDENTIFIED BY "testpass";. See for more information on this.
And then, in my project, I would have:
let connection = mysql.createConnection({
host: "localhost",
user: "test",
password: "testpass",
database: "mydatabase"
});
If you are using MAMP please note that mysql default db_port is set to 8889 so you for this purpose I had to change it to 3306 (or whatever your app mysql db_port is set to).
My issue was that node server was connecting using port 3306, so it was giving the error below then crashing but mysql was up and seemed to establishing a connection through localhost, although I couldnt test it because node server was down.
errno: -61,
code: 'ECONNREFUSED',
syscall: 'connect',
address: '127.0.0.1',
port: 3306,
fatal: true
Once I changed the port on MAMP mysql from 8889 to 3306, node server established connection through port 3000 and giving the statement below:
server running on port 3000
The solution is: 2
I use Windows 10 and I have Windows Subsystem For Linux (WSFL). I can execute my project from the WSFL console, but my MySQL is installed in Windows and they can not connect, however when I execute my project from a Windows console then it works without any problems.

How to tell node.js that mysql is not running on default port?

I'm having a problem similar to this person's: connect ECONNREFUSED - node js , sql
I'm trying to connect app.js to an existing database running as part of MAMP. MAMP runs mysql on port 8889; how do I tell node.js which port to find mysql on?
When you are initializing the mysql client, along with username and password, you can pass a different value for port.
const client = mysql.createClient({
user: '??',
password: '??',
port: 8889
});
For those initializing the mysql connection object using mysql.createPool({...}), it's the same solution as the accepted answer. For Reference
const connection = mysql.createPool({
host: ...,
port: 8889,
user: ...,
password: ...,
});