node.js 如何使用 express.js 将 mysql 连接正确传递到路由

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16800418/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 14:38:08  来源:igfitidea点击:

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

node.jsexpressnode-mysql

提问by anonymousfox

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 file loop in routes), meaning I can't just pass in the connection to routes that need it. I either need to pass it to every route or none at all. I didn't like the idea of passing it to ones that dont need it so I created a dbConnection.js that the routes can individually import if they need. The problem is that I dont think I am doing it correctly. As of now, my dbConnection.js contains:

我试图找出在我的 express.js 路由之间传递 mysql 连接(使用 node-mysql)的最佳方法。我正在动态添加每个路由(在路由中使用 for each file 循环),这意味着我不能只将连接传递给需要它的路由。我要么需要将它传递到每条路线,要么根本不需要。我不喜欢将它传递给不需要它的想法,所以我创建了一个 dbConnection.js,如果需要,路由可以单独导入。问题是我不认为我做对了。截至目前,我的 dbConnection.js 包含:

var mysql = require('mysql');
var db = null;
module.exports = function () {
    if(!db) {
            db = mysql.createConnection({
                socketPath: '/tmp/mysql.sock',
            user: '*********',
            password: '*********',
            database: '**********'
        });
    }
    return db;
};

And I am importing it into each route using:

我使用以下方法将其导入到每条路线中:

var db = require('../dbConnection.js');
var connection = new db();

But I would like to do it like this:

但我想这样做:

var connection = require('../dbConnection.js');

When I try it like this, however, I get an error saying connection has no method 'query' when I try to make a query.

然而,当我像这样尝试时,当我尝试进行查询时,我收到一条错误消息,指出连接没有方法“查询”。

回答by Daniel

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.

我发现使用 node-mysql 的池对象更可靠。这是我如何设置我的。我使用环境变量来获取数据库信息。使其远离回购。

database.js

数据库.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);
  });
};

回答by Banditvibe

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

如果使用 db() 而不是 new db(),您的解决方案将起作用,它返回一个对象而不是 db 连接

var db = require('../dbConnection.js');
//var connection = new db();
var connection = db();