Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nodejs (Express) connecting MySQL - Local and Remote connection different?

guys. I am learning how to use Express to connect to remote MySQL. So, I started out doing it on my local machine (a local MySQL server). After I have succeeded on the local environment, I tried changing the the connection to a remote MySQL hosting (at DB4Free). Yes, I have succeeded on the localhost. However, whenever I run a Get/Post to the remote MySQL Server, my console show me the error below. I'll attach the related segment of codes below here. I have been trying it the whole afternoon. Hope that someone here can enlighten on this matter. Thank you in advance guys :)

This is the error shown in my console

enter image description here

My file for connecting db is as below - ConnectionString.js

var mysql = require("mysql");

var pool = mysql.createPool({
        connectionLimit : 100,
        host     : '85.10.205.173:3306',
        user     : '******* ',
        password : '*******',
        database : '*******',
    });

exports.getConnection = function(callback) {
  pool.getConnection(function(err, conn) {
    if(err) {
      return callback(err);
    }
    callback(err, conn);
  });
};

Portion of my file for the routes and query is this

var express = require('express');
var router = express.Router();
var mysql      = require('mysql');
var conn = require('../database/ConnectionString');

var result;

//Validate user login
router.get('/login', function(req, res, next) {

        conn.getConnection(
            function (err, client) {

                client.query('SELECT * FROM mt_User', function(err, rows) {
                    // And done with the connection.
                    if(err){
                        console.log('Query Error');
                    }

                    res.json(rows);
                    client.release();

                    // Don't use the connection here, it has been returned to the pool.
                });

        });     

});
like image 460
DriLLFreAK100 Avatar asked Dec 07 '22 22:12

DriLLFreAK100


1 Answers

Alright, I have found the issue. It seems that the mysql package in npm requires that the host and port to be defined separately. After tuning it to this code below for my ConnectionString.js file. It finally works.

var mysql = require("mysql");

var pool = mysql.createPool({
        connectionLimit : 100,
        host     : '85.10.205.173',
        port     :  3306,
        user     : '*******',
        password : '*******',
        database : '*******',
    });

exports.getConnection = function(callback) {
  pool.getConnection(function(err, conn) {
    if(err) {
      return callback(err);
    }
    callback(err, conn);
  });
};
like image 87
DriLLFreAK100 Avatar answered Dec 11 '22 07:12

DriLLFreAK100