简体   繁体   中英

Connecting to MySQL on Node.js not initialized

I can't connect to the MySQL-database. I've googled some solutions, but none seems to work, or perhaps I haven't understood them. This is the setup:

let express = require("express");
let mysql      = require("mysql");
let http = require("http");

let app  = express();
http.createServer(app).listen(8000, function() {
    console.log("Listening on http://localhost:" + port)
});

var connection = mysql.createConnection({
    host: "127.0.0.1",
    user: "root",
    password: process.env.DB_PASSWORD,
    database: "users",
    port: 8000
});

connection.connect();

connection.query("SELECT * FROM user", function(err, rows, fields)
{
    if (err) {
        console.error("error connecting: " + err.stack);
        return;
    }

    console.log(rows[0]);
});

connection.end();

Tried to setup the connection with "socketPath" and with another port, but they both returned error:

Error: connect ECONNREFUSED 127.0.0.1:3306
at Object.exports._errnoException (util.js:1034:11)
at exports._exceptionWithHostPort (util.js:1057:20)
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1099:14)
--------------------
at Protocol._enqueue (/vagrant/node_modules/mysql/lib/protocol/Protocol.js:141:48)
at Protocol.handshake (/vagrant/node_modules/mysql/lib/protocol/Protocol.js:52:41)
at Connection.connect (/vagrant/node_modules/mysql/lib/Connection.js:130:18)
at Object.<anonymous> (/vagrant/app.js:12:12)
at Module._compile (module.js:571:32)
at Object.Module._extensions..js (module.js:580:10)
at Module.load (module.js:488:32)
at tryModuleLoad (module.js:447:12)
at Function.Module._load (module.js:439:3)
at Module.runMain (module.js:605:10)

When the connection and listen listens on same port, it doesn't return any errors, but the connection doesn't seem to initialize.

console.log(connection.connect()); // -> undefined

I'm very new to using MySQL to node so I'm probably doing this all wrong, but can't figure out what the problem is

For MAC users using MAMP

var con = mysql.createConnection({
    host: "localhost",
    user: "root",
    password: "root",
    database: "databasename",
    socketPath: '/Applications/MAMP/tmp/mysql/mysql.sock'
});

socketPath points to MAMP "mysql.sock" to permit the NodeJS/Mysql connection.

NOTE: the above connection also solves "Error: connect ECONNREFUSED 127.0.0.1:3306".

I hope this helps someone.

Change your connection.connect() to

connection.connect(function(err) {
  if (err) {
    console.error('error connecting: ' + err.stack);
    return;
  }

  console.log('connected as id ' + connection.threadId);
});

so you can see errors.

EDIT: Check bind-address and port in mysql config file ( /etc/mysql/my.cnf ). If your mysql server is running on host environment and node is running in guest (any virtualization like docker), set mysql server to listen on your local ip (eth0 like 192.168.0.x) and use same address in node config

As it turns out, I was a bit stupid. I was running the application on a Vagrant-server(virtual server), and I was trying to connect to my local-server. As soon as I tried to connect to the vagrant-server, everything worked properly. I also didn't have mysql-server properly installed to my vagrant machine.

if you don't set the port or set it to mysql default port ie 3306 it works fine.

var connection = mysql.createConnection({
    host: "127.0.0.1",
    user: "mysqluser",
    password: 'password',
    database: "yourdatabase"
});

I don't know the exact cause(although i tried with different ports), why it's not running on different ports but here is a link that shows how to use different port number for connecting mysql.

FYI: You are setting your app to run on 8000 and again the port mysql using in your app is 8000.You must change it to something else.

You have to set socketPath and before you run your script make sure your MAMP is running or not.

var con = mysql.createConnection({
    host: "localhost",
    user: "root",
    password: "root",
    socketPath: '/Applications/MAMP/tmp/mysql/mysql.sock'
});

Remove your port key value(port: 8000) and socketPath if you added, from sql configuration, and try.

var connection = mysql.createConnection({
    host: "127.0.0.1",
    user: "root",
    password: "root",
    database: "users"
});

Actually you occupied 8000 port by node server so you can't assign same port to different process.

Second mysql is running on port 3306. so you could not connect mysql through different port.

You can use different port for mysql but by some proxy pass mechanism or by running mysql itself on specific port.

Please follow simple steps to start (Worked on windows Machine):

  1. Download and install MySQL from following link click here . 点击这里
  2. Configure downloaded file (I had kept default config parameters). Please check this video link for reference
  3. Make sure MySQL server status is on.
  4. Now you can check connection status by using below node code.

 const mysql = require('mysql'); const connection = mysql.createConnection({ host: 'localhost', user: 'root', password: 'password', port: 3306 }); connection.connect((err) => { if (err) throw err; console.log('Connected to MySQL Server'); })

Start Your Mysql Server from your Xampp Control panel

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