解决方法
实际上我问这个问题是自己回答的,因为我相信我有一个值得分享的答案,而我在其他地方找不到文件化的解决方案.另外在几个问题(
#118,#164,#165)在node-mssql中讨论了这个话题.
这是我的解决方案:
在server.js中
var express = require('express'); var sql = require('mssql'); var config = {/*...*/}; //instantiate a connection pool var cp = new sql.Connection(config); //cp = connection pool //require route handlers and use the same connection pool everywhere var set1 = require('./routes/set1')(cp); var set2 = require('./routes/set2')(cp); //generic express stuff var app = express(); //... app.get('/path1',set1.get); app.get('/path2',set2.get); //connect the pool and start the web server when done cp.connect().then(function() { console.log('Connection pool open for duty'); var server = app.listen(3000,function () { var host = server.address().address; var port = server.address().port; console.log('Example app listening at http://%s:%s',host,port); }); }).catch(function(err) { console.error('Error creating connection pool',err); });
在routes / set1.js
var sql = require('mssql'); module.exports = function(cp) { var me = { get: function(req,res,next) { var request = new sql.Request(cp); request.query('select * from test',function(err,recordset) { if (err) { console.error(err); res.status(500).send(err.message); return; } res.status(200).json(recordset); }); } }; return me; };