0

I have tried to connect NodeJS to mysql on Windows 10, but continuously failed to. The following is the code, which from https://www.w3schools.com/nodejs/nodejs_mysql_create_db.asp

var mysql = require('mysql');

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

con.connect(function(err) {
  if (err) throw err;
  console.log("Connected!");
  con.query("CREATE DATABASE mydb", function (err, result) {
    if (err) throw err;
    console.log("Database created");
  });
});

and the following is the error message when I run code.

  if(err) throw err;
          ^

Error: connect ECONNREFUSED 127.0.0.1:3306
    at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1134:16)
    --------------------
    at Protocol._enqueue (C:\Users\tete6\NodeJS\node_modules\mysql\lib\protocol\Protocol.js:144:48)
    at Protocol.handshake (C:\Users\tete6\NodeJS\node_modules\mysql\lib\protocol\Protocol.js:51:23)
    at Connection.connect (C:\Users\tete6\NodeJS\node_modules\mysql\lib\Connection.js:116:18)
    at Object.<anonymous> (C:\Users\tete6\NodeJS\demo_db_connection.js:9:5)
    at Module._compile (internal/modules/cjs/loader.js:955:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:991:10)
    at Module.load (internal/modules/cjs/loader.js:811:32)
    at Function.Module._load (internal/modules/cjs/loader.js:723:14)
    at Function.Module.runMain (internal/modules/cjs/loader.js:1043:10)
    at internal/main/run_main_module.js:17:11 {
  errno: 'ECONNREFUSED',
  code: 'ECONNREFUSED',
  syscall: 'connect',
  address: '127.0.0.1',
  port: 3306,
  fatal: true
}

To solve this error, I tried ...

  1. change "localhost" -> "127.0.0.1", but failed.
  2. add "port: 3306", but failed.
  3. check if the port is available to be connected, and I found that it's never my port, fireWall problem. My xampp's mysql works well.
  4. Even mongoDB module triggers this same error message.

I gleaned some info that this econnrefused error message is mainly the problem of NodeJS, not of sql module.

Is anyone to show me silver shining from this?

1 Answers1

0

Have you started your XAMPP Server?

connect ECONNREFUSED 127.0.0.1:3306 -- this error came, when you not started your XAMPP server.

At the first you should right install mysql into windows 10

and see this video link how to connect to mysql with node js

mohammad javad ahmadi
  • 2,031
  • 1
  • 10
  • 27