Vikas Kumar Vikas Kumar - 1 month ago 14
Javascript Question

Why the server not accessing connection variable?

I'm trying to retrieve data from database using Node.js restify framework. The server is running fine but when I visit http://localhost:8081/get I get this error:

{
"code": "InternalError",
"message": "connectionPool is not defined"
}


Here's my code:

server.js

require('./app/core/routes.js');


routes.js

var restify=require('restify');
var fs=require('fs');
var controllers = {};
controllers_path = process.cwd() + '/app/controllers';
fs.readdirSync(controllers_path).forEach(function (file) {
if (file.indexOf('.js') != -1) {
controllers[file.split('.')[0]] = require(controllers_path + '/' + file);
}
});
var server=restify.createServer();
server.get('/get', controllers.article.printHello);
server.listen(8081, function (err) {
if (err)
console.error(err);
else
console.log('App is ready at : ' + 8081);
});


article.js

var something2=require('../core/connection.js');
something2.something();
exports.printHello= function(req, res, next){
connectionPool.getConnection(function (err, connection) {
if (err) {
res.send({
Error: err,
Message: "Can't connect Database."
});
} else {
//queries
connection.query("SELECT * FROM book", function (err, rows, fields) {
res.send({
json: rows
});
});
}
});
};


connection.js

var mysql = require('mysql');
exports.something = function () {
var connectionPool = mysql.createPool({
host: 'localhost',
user: 'root',
password: '',
database: 'books'
});
}

Answer

You have to return your variable connectionPool in your connection.js's something function.

connection.js

var mysql = require('mysql');
exports.something = function () {
    var connectionPool = mysql.createPool({
        host: 'localhost',
        user: 'root',
        password: '',
        database: 'books'
    });
return connectionPool; // notice here
}

article.js

var something2=require('../core/connection.js');
var connectionPool =  something2.something(); //notice here
exports.printHello= function(req, res, next){
    connectionPool.getConnection(function (err, connection) {
        if (err) {
            res.send({
                Error: err,
                Message: "Can't connect Database."
            });
        } else {
            //queries
            connection.query("SELECT * FROM book", function (err, rows, fields) {
                res.send({
                    json: rows
                });
            });
        }
    });
};