Reputation: 14824
I have declared mysql
, and my connection in app.js
like so:
var mysql = require('mysql');
var connection = mysql.createConnection({
host: '192.168.1.75',
user: 'dev',
password: 'devaccount',
database: 'PugIt'
});
app.set('connection', connection);
And in my User.js
for registration I have:
router.route('/register/steam/finish')
.get(function(req, res) {
res.render('user/register_steam');
})
.post(function(req, res) {
var connection = req.app.get('connection');
connection.connect();
// Look For Users
connection.query("SELECT * FROM Users", function(err, rows, fields) {
console.log('We Found Something!');
});
connection.end();
});
When the page first loads and I hit register, it works fine, but if I hit the button a second time I get a 500
error on my server.
But if I manually declare var connection
inside each route
file, this does not happen.
How come I cannot use req.app.get
with MySQL, I used this method when I used to use MongoDB
which worked great that way I had one main config in app.js I could alter to change in all route files if I needed. Not sure why I'm getting a 500
error on second POST
Upvotes: 1
Views: 1401
Reputation: 106696
I think the connection.connect()
and connection.end()
on every POST
request is causing problems. Drop those two lines and you should be good to go. This way the connection is only established once and all requests can re-use the same connection without constantly trying to tear it down and bring it back up again.
You can also create a pool of mysql connections if you find yourself needing greater concurrency with your database queries.
Upvotes: 1