【问题标题】:Best way to open a mysql connection in Express 4在 Express 4 中打开 mysql 连接的最佳方法
【发布时间】:2015-05-14 08:16:12
【问题描述】:

所以我已经安装了 node-mysql 并在 express 4 上运行。我是 express 的新手,想学习数据库连接的最佳实践。我目前有

app.js

var mysql = require('mysql'); //set up mysql here

var routes = require('./routes/index');
var users = require('./routes/users');
var work = require('./routes/work');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

// uncomment after placing your favicon in /public
//app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')))

app.use('/', routes);
app.use('/users', users);
app.use('/work', work); //send the mysql var to work..?
app.use(mysql, work);

如您所见,我在 app.js 中设置了 mysql,如何将这个变量发送到 work.js。我试过了:

app.use(mysql, work);

但是当我在 work.js 文件中访问 mysql 时,我收到一条错误消息。

编辑: 我已将 var mysql = require('mysql'); //set up mysql here 添加到我的 work.js 页面,它工作正常,我应该从 app.js 中删除它吗?这方面的最佳做法是什么?我不想每次在不同页面上查询时都打开与数据库的新连接,对吧?

【问题讨论】:

    标签: javascript mysql node.js express


    【解决方案1】:

    您可以在类似的其他文件中使用 mysql 变量(以用户路由为例):

    app.js:

    var mysql = require('mysql'); //set up mysql here
    
    var users = require('./routes/users')(mysql);
    
    var app = express();
    

    users.js:

    exports = module.exports = function (mysql) {
    
       console.log(mysql);
    
       // do what you have to do with the mysql variable
    
    }
    

    【讨论】:

      猜你喜欢
      • 2010-09-09
      • 2019-10-18
      • 2014-12-04
      • 1970-01-01
      • 2018-10-31
      • 1970-01-01
      • 1970-01-01
      • 2010-12-12
      • 1970-01-01
      相关资源
      最近更新 更多