Why Is It Showing Connection Not Defined?
Solution 1:
No need for the .js
file extension, it's automagically added for you.
The code below uses standard error-first callbacks
webFrontend.js
var connection = require('../Routes/connection');
exports.getIndivRecords = function(req, res, next){
// connection takes a standard error-first callbackconnection(function(err, conn){
if (err) {
// Handle the error returnedconsole.log(err);
}
// The database connection is available here as connconsole.log( "Connection:" + conn);
// presumably you want to do something here// before sending the response
res.send({
Result: conn + "This is result"
});
});
returnnext();
};
connection.js
var mySQL = require('mysql');
var connectionPool = mySQL.createPool({
host: 'localhost',
user: 'root',
password: '',
database: 'rockcity_followme'
});
var getConnection = function (cb) {
connectionPool.getConnection(function (err, connection) {
// pass the error to the callbackif (err) {
returncb(err);
}
cb(null, connection);
});
};
module.exports = getConnection;
Solution 2:
First of all @Dan Nagle was right no need of .js
Second You are getting the connection undefinded
because still the method doesnt returned with result.
Use promise to call your Connection.js method
Your node is single threaded async execution, He doest wait for the method to return a result
1) Problem with your javascript is that
var connection=connObj.connExport();
in Creation stage connection
was defined by javascript as undefined and as
connObj.connExport();
as still not returned with answer
it executed this function in which connection was undefined
exports.getIndivRecords= function(req, res, next){
res.send({
Result: connection+"This is result"
});
Use promise read this first so you can understand something about promise and callback if you are unable to solve than comment i will play with it.But first you try.Thanku
Understanding promises in node.js
Ok Try This I have used promise here
var connObj = require('../Routes/connection');
connObj.connExport().then(
function (connection) {
exports.getIndivRecords = function (req, res, next) {
res.send({
Result: connection + "This is result"
});
returnnext();
};
}).catch(function (err) {
res.status(400).send(err);
return;
});
var mysql = require('mysql');
exports.connExport = function () {
returnnewPromise(function (fulfill, reject) {
var connectionPool = mysql.createPool({
host: 'localhost',
user: 'root',
password: '',
database: 'rockcity_followme'
});
if (connectionPool) {
connectionPool.getConnection(function (err, connection) {
if (err) {
returnreject(err);
} else {
returnfulfill(connection);
}
});
} else {
var abc = "return error";
returnreject(abc);
}
});
}
Post a Comment for "Why Is It Showing Connection Not Defined?"