How to properly pass mysql connection to routes with express.js

坚强是说给别人听的谎言 提交于 2019-11-27 18:23:07

I find it more reliable to use node-mysql's pool object. Here's how I set mine up. I use environment variable for database information. Keeps it out of the repo.

database.js

var mysql = require('mysql');

var pool = mysql.createPool({
  host: process.env.MYSQL_HOST,
  user: process.env.MYSQL_USER,
  password: process.env.MYSQL_PASS,
  database: process.env.MYSQL_DB,
  connectionLimit: 10,
  supportBigNumbers: true
});

// Get records from a city
exports.getRecords = function(city, callback) {
  var sql = "SELECT name FROM users WHERE city=?";
  // get a connection from the pool
  pool.getConnection(function(err, connection) {
    if(err) { console.log(err); callback(true); return; }
    // make the query
    connection.query(sql, [city], function(err, results) {
      connection.release();
      if(err) { console.log(err); callback(true); return; }
      callback(false, results);
    });
  });
};

Route

var db = require('../database');

exports.GET = function(req, res) {
  db.getRecords("San Francisco", function(err, results) {
    if(err) { res.send(500,"Server Error"); return;
    // Respond with results as JSON
    res.send(results);
  });
};

your solution will work if use db() instead of new db(), which returns an object and not the db connection

var db = require('../dbConnection.js');
//var connection = new db();
var connection = db();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!