我有以下代码用于实现nodejs的rest api。
app.js
var connection = require('./database_connector');
connection.initalized(); //guys connection is i want to pass a connection varible to the model
var peson_model = require('./models/person_model')(connection); //this not working
var app = express();
app.use(bodyparser.urlencoded({extended: true}));
app.use(bodyparser.json());
app.get('/persons/', function(req, res) {
person_model.get(res); // retrive get results
});
// .............express port and listen
person_model.js
是一个模型类,应该基于 http 动词进行检索。例如,person.get
检索以下内容,并且当前只有一个方法,如下所示。
function Person(connection) {
this.get = function (res) {
connection.acquire(function(err, con) {
con.query('select * from person limit 3', function(err, result) {
con.release();
console.log("get called");
res.send(result);
});
});
};
}
// ** I want to pass a connection variable to the model
module.exports = new Person(connection);
在上面的代码中,var peson_model = require('./models/person_model')(connection);
不起作用。
如何传递连接变量并导出模块?
最佳答案
如果您从导出中返回一个函数,则可以传递您的参数。
module.exports = function(connection) {
return new Person(connection);
};
您需要设置 this.connection
并在您的函数中使用它。
关于javascript - 将参数传递给nodejs中的module.exports,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39331788/