【问题标题】:How to delegate route processing in express?如何在快递中委托路线处理?
【发布时间】:2016-03-01 20:15:40
【问题描述】:

我有一个带有 straitfort 路由处理的 expressjs 应用程序,如下所示:

app.route('/').get(function(req, res, next) {
   // handling code;
});

app.route('/account').get(function(req, res, next) {
   // handling code;    
});

app.route('/profile').get(function(req, res, next) {
   // handling code;
});

现在我将所有代码都放在路由处理程序中,但我想尝试将其委​​托给某些类,例如以下。

app.route('/').get(function(req, res, next) {
   new IndexPageController().get(req, res, next);
});

app.route('/account').get(function(req, res, next) {
   new AccountPageController().get(req, res, next);
});

app.route('/profile').get(function(req, res, next) {
   new ProfilePageController().get(req, res, next);
});

那么你对上面的方法有什么看法,也许你知道更好的方法?

【问题讨论】:

    标签: node.js express controller routes express-4


    【解决方案1】:

    正如您在Express Response documentation 中看到的 - 响应 (req) 可以通过几种方法向客户端发送信息。最简单的方法是使用req.render,例如:

    // send the rendered view to the client
    res.render('index');
    

    知道这意味着你可以在另一个函数中做任何你想做的事情,最后只需调用res.render(或任何其他向客户端发送信息的方法)。例如:

    app.route('/').get(function(req, res, next) {
       ndexPageController().get(req, res, next);
    });
    
    // in your IndexPageController:
    
    function IndexPageController() {
        function get(req, res, next) {
            doSomeDatabaseCall(function(results) {
                res.render('page', results);
            }
        }
    
        return {
            get: get
        }
    }
    // actually instantiate it here and so module.exports
    // will be equal to { get: get } with a reference to the real get method
    // this way each time you require('IndexPageController') you won't
    // create new instance, but rather user the already created one
    // and just call a method on it.
    module.exports = new IndexPageController();
    

    对此没有严格的方法。您可以传递响应和其他人调用渲染。或者您可以等待另一件事发生(例如 db 调用),然后调用 render。一切由你决定——你只需要以某种方式向客户发送信息:)

    【讨论】:

    • 感谢您的回复。我只是担心每次为每个请求创建新对象。
    • 然后创建单例文件(带有单个实例)。这样,您将拥有一个实例并为每个请求调用它的方法。刚刚更新了我的答案。
    • 感谢您的回复,但我想在每个请求上创建新的控制器实例。它会影响性能还是增加内存?
    • “我只是担心每次为每个请求创建新对象。”,“我想在每个请求上创建新的控制器实例”。好吧,伙计,一切都取决于您 :) 当然会产生影响,但这完全取决于您的代码。只要你可以调用不同的函数,我没有看到任何创建新控制器的想法..
    猜你喜欢
    • 2016-08-12
    • 2011-01-29
    • 2013-04-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多