Home > Blockchain >  Node cannot connect to MySQL for version 17
Node cannot connect to MySQL for version 17

Time:01-17

I have written a simple test file for Node to access MySQL on my Ubuntu server. For Node versions 14,15,16 it can connect. For Node versions 17,18,19, it cannot.

I am using MySQL 8.0.31 on Ubuntu 20.04. The test file is called test.js and has the following code:

var mysql = require('mysql');

var con = mysql.createConnection({
  host: "localhost",
  user: "root",
  password: "correctpasswordhere"
});

con.connect(function(err) {
  if (err) throw err;
  console.log("Connected!");
});

I use nvm to select the Node version I want to test. For example, I run

nvm install 16
node test.js

Output: Connected!

But when I use:

nvm install 17
node test.js

Output:


if (err) throw err;
           ^

Error: connect ECONNREFUSED ::1:3306
    at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1195:16)
    --------------------
    at Protocol._enqueue (/root/gatsby_test/node_test/node_modules/mysql/lib/protocol/Protocol.js:144:48)
    at Protocol.handshake (/root/gatsby_test/node_test/node_modules/mysql/lib/protocol/Protocol.js:51:23)
    at Connection.connect (/root/gatsby_test/node_test/node_modules/mysql/lib/Connection.js:116:18)
    at Object.<anonymous> (/root/gatsby_test/node_test/test.js:9:5)
    at Module._compile (node:internal/modules/cjs/loader:1099:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
    at Module.load (node:internal/modules/cjs/loader:975:32)
    at Function.Module._load (node:internal/modules/cjs/loader:822:12)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:77:12)
    at node:internal/main/run_main_module:17:47 {
  errno: -111,
  code: 'ECONNREFUSED',
  syscall: 'connect',
  address: '::1',
  port: 3306,
  fatal: true
}

Node.js v17.9.1

I'd like to use the latest version of Node but I need it to connect to MySQL. I've Googled around but have only found people referring to having the wrong login credentials. Anyone know what's going on? Thanks!

CodePudding user response:

Don't use localhost as hostname if you want to prevent the client from connecting to MySQL over IPv6 (which is what's happening), use 127.0.0.1 instead.

Alternatively, make MySQL listen on IPv6 too.

  • Related