Reputation: 419
i am trying to connect mysql, but it is showing me req.getConnection is not a function
Bellow is the code snipet which i have used.
In app.js
var mysql = require('mysql'),
connection = require('express-myconnection'),
dbOptions = {
host: 'localhost',
user: 'root', password: '',
port: 3306,
database: 'nodejs'
};
app.use(connection(mysql, dbOptions, 'request'));
In Customers.js
exports.list = function(req, res, next) {
req.getConnection(function(err, connection) {
if (err) return next(err);
connection.query('SELECT * FROM customer', function(err, rows) {
if (err) console.log("Error Selecting : %s ", err);
res.render('customers', {
page_title: "Customers - Node.js", data: rows
});
});
});
};
Can you please check what is have done wrong. I am pretty new in nodejs, so may be i am missing something.
If you want to check my complete package, please follow bellow URL, i have push all code in my git repository https://github.com/chiraggmodi/nodeCrud
Upvotes: 0
Views: 2329
Reputation: 203359
You need to move this line:
app.use(connection(mysql, dbOptions, 'request'));
Right now, it's declared after your routes, which means that requests will never pass through it (that's how Express works: requests are passed through both middleware and route handlers in order of their declaration).
If you use it to a location in the code before the routes that require req.getConnection()
to work (perhaps here), requests will first pass through the express-myconnection
middleware and then get passed to the route handlers, making sure that req.getConnection()
will be available inside those route handlers.
EDIT: on closer look, your customer routes are also incorrect.
You have this:
router.get('/', function(req, res, next) {
res.render('customers', customers.list);
});
But customer.list
is a route handler in itself, not something you should pass to res.render()
. Instead, try this:
router.get('/', customers.list);
(and similarly for all the other routes in customers_route.js
)
Upvotes: 1