如何使用 express.js 将 mysql 连接正确传递到路由 [英] How to properly pass mysql connection to routes with express.js

查看:29
本文介绍了如何使用 express.js 将 mysql 连接正确传递到路由的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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:

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();

但我想这样做:

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.

推荐答案

我发现使用 node-mysql 的池对象更可靠.这是我如何设置我的.我使用环境变量来获取数据库信息.将其保留在 repo 之外.

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.

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);
    });
  });
};

路线

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);
  });
};

这篇关于如何使用 express.js 将 mysql 连接正确传递到路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆