【问题标题】:How to include js files in my EJS templates in node.js using express 3.x如何使用 express 3.x 在 node.js 中的 EJS 模板中包含 js 文件
【发布时间】:2012-08-11 11:00:02
【问题描述】:

我看到的所有示例都使用app.dynamicHelpers 来提供一种在我的视图模板中访问我的javascript 文件的方法。但是在 express 3.x 中没有明确的方法可以做到这一点。 migration docs 说“使用中间件”。我对“中间件”的概念比较陌生,不知道如何实现它。

我只想知道在我的视图模板中包含 javascript 文件的最优雅的方式。

【问题讨论】:

    标签: javascript node.js express ejs


    【解决方案1】:

    中间件是Connect 的基础,Express 正是基于该基础。简而言之,它允许您将传入 HTTP 请求和响应的多个处理程序链接在一起。您在 Express 应用程序中为每个 app.use() 提供的参数基本上是一个“中间件”,并且是具有以下签名的回调 function (request, response, next),其中 next 是链中要调用的下一个中间件回调。以下都是中间件(最后一个是error handler,有4个参数签名):

    app.use(express.bodyParser());
    app.use(express.methodOverride());
    app.use(app.router);
    app.use(function(err, req, res, next){
      // logic
      next();
    });
    

    就从 Express 2 到 3.x 的迁移而言,迁移具体是:

    app.dynamicHelpers()(使用中间件+res.locals

    因此,举一个人为的例子,您之前可能在外部 js 文件中有一个辅助函数,而 required 将它用于您的 dynamicHelper

    //helpers.js
    exports.dynamicHelpers = {
      currentUser: function(req, res) {
        return req.user;
      }
    };
    
    // app.js
    var helpers = require('./helpers').dynamicHelpers;
    
    app.dynamicHelpers(helpers);
    

    通过一些重组,您现在可以执行以下操作:

    //locals.js
    exports.setLocals = function(req, res, next){ //<- middleware function
      res.locals.currentUser = req.user;
      res.locals.otherVariable = ...;
      next();
    }
    
    //app.js
    var locals = require('./locals').setLocals;
    ...
    app.use(locals);
    

    这是一个很好的blog,对中间件与 pre-3.x Express 中的dynamicHelpers 进行了对比,但概念是相同的。唯一的区别是文章中使用的res.local(name, value) 现在是deprecated 用于res.locals.name = valueres.locals({ name: value })

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-07-20
      • 2017-02-17
      • 1970-01-01
      • 2016-02-24
      • 1970-01-01
      • 2012-01-29
      • 2014-08-26
      • 1970-01-01
      相关资源
      最近更新 更多