简体   繁体   中英

Connection refused when connecting to MySql using NodeJS mysql2

I am running a NodeJS app hosted on a (linux) dedicated Plesk server, under a subdomain. Trying to connect to a MariaDB mysql server. The NodeJS code:

const mysql = require('mysql2');

const con = mysql.createConnection({
  host: "localhost",
  user: "username",
  password: "password",
  database: "myDatabase"
});
global.MYSQL_CONNECTION = con;

function Connect(onSuccess){
    con.connect(function(err) {
        if (err) throw err;
        console.log("MySQL connected successfully.");
        onSuccess(con);
      });
}

When I run this I get the following error:

Error: connect ECONNREFUSED ::1:3306
    at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1195:16) {
  errno: -111,
  code: 'ECONNREFUSED',
  syscall: 'connect',
  address: '::1',
  port: 3306,
  fatal: true
}

However, when I run mysql -hlocalhost -uusername -ppassword on my bash terminal it connects fine, meaning the credentials are correct and the user has permissions.

What could be causing this?

Figured out the solution to this. All I had to do was to change the host to 127.0.0.1:

const con = mysql.createConnection({
  host: "127.0.0.1",
  user: "username",
  password: "password",
  database: "myDatabase"
});

I am unsure of the reason. It most probably has something to do with the fact that this runs on a subdomain. Would be great if anyone could specify the reason.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM