Sunday, 11 June 2017

I can't connect to my mysql database with Node.js (connection.connect issue)

I cannot connect to my local mysql database on my personal computer from Node.js using the mysql node package. My Node.js program is on the same computer as the mysql database so no networking should be required. I have tried multiple solutions on stack overflow and none seem to work.

My directory structure:

project_root/ 
    mysql/         
        connection.js
    node_modules/
        ....
    server.js
    package.json

The contents of connection.js is shown below and the error occurs on the line with "connection.connect". I know this because the callback function running "function(err)" prints "Mysql connection error" and then "null" in the console.

var fs = require('fs');
var mysql = require('mysql');

var connection_data = JSON.parse(fs.readFileSync('../config/mysql.json', 'utf8'));

var connection = mysql.createConnection({
    host : connection_data['host'],
    user : connection_data['user'],
    password : connection_data['passwd'],
    database: connection_data['db'],
    charset: "utf8_general_ci",
    socketPath : '/tmp/mysql.sock'
});

export_connection = connection.connect(function(err) {
    console.log("Mysql connection error");
    console.log(err);
});

module.exports = export_connection

Other links have suggested looking at mysql status in the command line which is given below. I have even set the Node.js mysql connection to connect to the same socket shown in the status.

mysql> status 
--------------
mysql  Ver 14.14 Distrib 5.7.18, for osx10.12 (x86_64) using  EditLine wrapper

Connection id:      237509
Current database:   
Current user:       root@localhost
SSL:            Not in use
Current pager:      stdout
Using outfile:      ''
Using delimiter:    ;
Server version:     5.7.18 MySQL Community Server (GPL)
Protocol version:   10
Connection:     Localhost via UNIX socket
Server characterset:    latin1
Db     characterset:    latin1
Client characterset:    utf8
Conn.  characterset:    utf8
UNIX socket:        /tmp/mysql.sock
Uptime:         1 day 8 hours 9 min 18 sec

Note that connection_data['host'] is 127.0.0.1, connection_data['user'] is root and connection_data['db'] corresponds to an existing database.



via jacksonSmith

No comments:

Post a Comment