【问题标题】:Pass variable to expressjs 3 routes将变量传递给 expressjs 3 条路线
【发布时间】:2012-08-19 22:34:29
【问题描述】:

我有一个 ExpressJS 3 应用程序并将我的路线放在一个单独的文件中。我想在我的 app.js 中声明一些在路由文件中可用的配置 - 在路由定义本身之外。

在我的 app.js 中,我想做一些事情,例如:

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

然后在我的 routes/index.js 文件中我希望能够做到这一点:

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');
    }
  });
};

我看过一些与此相关的帖子,但没有一个真正解决我正在寻找的内容。我知道我可以将路由包装在一个函数中,但希望有一种替代方法可以让我的代码尽可能保持原样。

【问题讨论】:

  • 我刚刚看到stackoverflow.com/questions/10090414/… 上的最后一篇文章,它建议将 ap 声明为全局。这样做有什么缺点吗?因为这对我有用。
  • 用“app.set”替换你的“app.get”,它应该可以工作

标签: node.js express


【解决方案1】:

我只是创建了一个单独的 config 模块来保存我的配置,并且在任何需要来自配置的信息的模块中,我只是像往常一样需要它。当更松散耦合的方法工作得很好时,为什么还要将 express 加入混合中。

config.js

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

routes.js

var config = require("./config");
console.log(config.pathToModels);

【讨论】:

    【解决方案2】:

    只需将 app 作为参数传递给 `routes/index.js':

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

    更新:这应该是

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

    routes/index.js:

    var app;
    exports=function(whichApp) {
    

    更新:这应该是

    exports.init=function(whichApp) {
    
      app=whichApp;
      // do initialization stuff
      return exports;
    }
    
    exports.list=...
    

    【讨论】:

    • 将开头的require改为require('./routes/index.js').init(app);,第二行index.js改为exports.init=function(...)
    猜你喜欢
    • 1970-01-01
    • 2013-04-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多