当前位置: 动力学知识库 > 问答 > 编程问答 >

node.js - Pass variable to expresjs 3 routes

问题描述:

I have an ExpressJS 3 app and have my routes in a separate file. I'd like to declare some configs in my app.js that are available in the routes file - outside of the route definitions themselves.

In my app.js I would like to do something such as:

app.set('path_to_models', '/path/models/');

Then in my routes/index.js file I would like to be able to do this:

var Product = require(app.get('path_to_models') + 'product');

exports.list = function(req, res){

return Product.find(function (err, products) {

if (!err) {

res.render('product/manage', { products: products });

} else {

res.render('5xx');

}

});

};

I've seen a few posts related to this but none really addressed what I am looking for. I know that I can wrap the routes in a function but would like an alternative way that will keep my code as is if at all possible.

Thanks

网友答案:

I just make a separate config module that holds my configuration and in any module that needs info from the config, I just require it as normal. Why drag express into the mix when a more loosely coupled approach works just fine.

config.js

exports.pathToModels = "/path/to/models";

routes.js

var config = require("./config");
console.log(config.pathToModels);
网友答案:

Simply pass app as an argument to `routes/index.js':

var routes = require('./routes/index.js')(app);

UPDATED: This should be

var routes = require('./routes/index.js').init(app);

and in routes/index.js:

var app;
exports=function(whichApp) {

UPDATED: This should be

exports.init=function(whichApp) {

  app=whichApp;
  // do initialization stuff
  return exports;
}

exports.list=...
分享给朋友:
您可能感兴趣的文章:
随机阅读: