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

后端 未结 2 1811
太阳男子
太阳男子 2020-12-04 18:28

I am trying to figure out the best way to pass a mysql connection (using node-mysql) between my routes for express.js. I am dynamically adding each route (using a for each f

相关标签:
2条回答
  • 2020-12-04 18:53

    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);
      });
    };
    
    0 讨论(0)
  • 2020-12-04 18:57

    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();
    
    0 讨论(0)
提交回复
热议问题