nodejs:访问路由中的变量

时间:2017-10-22 00:29:33

标签: node.js express sequelize.js restify

以下是我routes.js的样子:

module.exports = function (server, db) {

    // Deals
    const deals = require('./controllers/deals');
    server.get('/deals', deals.findAll);
    server.get('/deals/:id', deals.findById);
    server.post('/deals', deals.add);
    server.put('/deals/:id', deals.update);
    server.del('/deals/:id', deals.delete);

}

如您所见,此处有serverdb个变量。但是,我不确定如何将这两个变量传递给deals.findAll以及其他REST方法。

以下是deals.findAll方法的外观:

const findAll = (req, res, next) => {
   // I need to access db here, so I can use Sequelize.
}

exports.findAll = findAll

我需要db的原因是Sequelize ORM。

1 个答案:

答案 0 :(得分:2)

您可以使用Function.prototype.bind()执行此操作:

module.exports = function (server, db) {

    // Deals
    const deals = require('./controllers/deals');
    server.get('/deals', deals.findAll.bind(null, server, db));
    server.get('/deals/:id', deals.findById.bind(null, server, db));
    server.post('/deals', deals.add.bind(null, server, db));
    server.put('/deals/:id', deals.update.bind(null, server, db));
    server.del('/deals/:id', deals.delete.bind(null, server, db));
}

Function.prototype.bind()方法预先这些参数,因此您需要将这些函数的参数修改为:

const findAll = (server, db, req, res, next) => {
   // server & db is set here
}