40

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)
Veve
  • 6,643
  • 5
  • 39
  • 58
Nico
  • 699
  • 1
  • 7
  • 16
  • 1
    Either your host is wrong, or you need to specify a port number. What is the port your mysqld is running on? After this has been sorted out, another possibility is that the ports on your host are blocked. What type of network are you connecting through? Typically we connect through localhost, or an internal network, and not the internet. – beiller May 15 '15 at 18:20
  • @beiller First I would thank you for your fast answer. I already tried it with setting the port in the configuration, but it also didn´t work. Mysql run on this port: `tcp 0 0 127.0.0.1:3306 0.0.0.0:* LISTEN 4322/mysqld` My server.js is running on port 2000, should the both running on the same port? What do you mean with "what type of network are you connecting through?" Tank you! – Nico May 15 '15 at 18:33
  • No they do not run on the same port. Your error message basically means "your connection was denied by the operating system" IE you never got close to touching the mysql server. By asking what network, I ask, is mysql and your node.js application running on the same physical server? – beiller May 15 '15 at 20:16
  • Yes mysql and node.js run on the same physical server, but I already solved the problem. I have to add the socketPath in the mysql connection configuration like this: `socketPath: '/var/run/mysqld/mysqld.sock'` But thank you for your time! :) – Nico May 15 '15 at 22:31
  • @Nico Will you accept the below answer or answer it yourself? Seems to show the solution you used. That answer also worked for me. – Hendeca Mar 16 '16 at 08:19
  • Check my answer in this post http://stackoverflow.com/a/37563064/2247612 – harishannam Jun 01 '16 at 08:16
  • I had this case. I did not specify port number so it was picking the default MySql port 3306 while it was running on 8889 in MAMP. – landrykapela Mar 23 '19 at 10:49
  • If you use MAMP Pro check also if the "Allow network access to MYSQL" is activated – miholzi Apr 17 '20 at 08:30

21 Answers21

55

I was having same problem but I solved this by changed

host:  'localhost'

to

host:   '127.0.0.1'
shrikantbishoye
  • 781
  • 6
  • 6
  • 8
    This worked. I'm just wondering what might be the explanation? I understand localhost's IP is 127.0.01 – Stanley Jan 30 '22 at 10:19
  • 1
    Thank you, it worked for me because I had node 19 running via nvm and it wasnt connected even though it did when using node 16. – Arham S C Jan 11 '23 at 07:38
54

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'
});
tdebroc
  • 1,436
  • 13
  • 28
23

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'
});
harishannam
  • 2,747
  • 3
  • 30
  • 39
5

Check your xampp server mysql is running or not

Kalpit tandon
  • 119
  • 1
  • 3
  • 10
3

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.

  1. Delete all node_modules
  2. Run "npm audit --force"
  3. 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).

3

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)
});
Tyler2P
  • 2,324
  • 26
  • 22
  • 31
Luqm
  • 31
  • 1
1

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.

Webwoman
  • 10,196
  • 12
  • 43
  • 87
Aditya Aggarwal
  • 159
  • 1
  • 9
1

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"
});
janithcooray
  • 188
  • 2
  • 15
1

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

toujames
  • 395
  • 5
  • 7
1

In my case, I downloaded XAMPP and checked for my username and password, and then it finally worked.

XAMPP > mySQL connected > phpmyadmin > user accounts: to see your account details!

Hope this helps.

Marcello Perri
  • 572
  • 7
  • 22
Judy
  • 11
  • 2
0

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

CLIFFORD P Y
  • 16,974
  • 6
  • 30
  • 45
0

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.

Doeun
  • 339
  • 3
  • 2
0

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:""
});
veben
  • 19,637
  • 14
  • 60
  • 80
salah
  • 1
0

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

0

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']

tomyhomie
  • 344
  • 2
  • 6
0

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

Syscall
  • 19,327
  • 10
  • 37
  • 52
0

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

General Grievance
  • 4,555
  • 31
  • 31
  • 45
Bala
  • 1
0

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

Dilshod Sh
  • 264
  • 2
  • 11
0

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

0

Re: the question about localhost vs 127.0.0.1 (I don't have enough reputation to add a comment :-( ) - https://stackoverflow.com/a/53533120/1804408

I had the same problem, I had host: "localhost" and fixed it by using "127.0.0.1".

I was getting the error Error: connect ECONNREFUSED ::1:3306 - I eventually realised that it was reporting the IPv6 local address. Even though I had the MySQL user defined with both @'%' and @'localhost' it looks like MySQL didn't like the IPv6 local address - probably something to do with my MySQL set up.

Pete
  • 21
  • 4
  • This does not really answer the question. If you have a different question, you can ask it by clicking [Ask Question](https://stackoverflow.com/questions/ask). To get notified when this question gets new answers, you can [follow this question](https://meta.stackexchange.com/q/345661). Once you have enough [reputation](https://stackoverflow.com/help/whats-reputation), you can also [add a bounty](https://stackoverflow.com/help/privileges/set-bounties) to draw more attention to this question. - [From Review](/review/late-answers/34697971) – Yogendra Jul 19 '23 at 08:33
  • You are absolutely correct, it doesn’t answer the original question, but it does shed some light on the question asked in the post on this thread that I referenced. Cheers. – Pete Jul 20 '23 at 16:01
-1

I am facing the same problem but I have done that:

  1. Turn ON your MySQL using XAMPP
  2. 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