【问题标题】:call app.get inside response.render在 response.render 中调用 app.get
【发布时间】:2013-06-12 19:42:20
【问题描述】:

如何在 response.render 中调用另一个快速路由。以下是我的代码 sn-p。我想在请求 /pages/performance 时渲染 performance.jade 并使用 /api/notifications 返回的数据填充翡翠

module.exports = function(app){
    app.get('/pages/performance', function(req, res){
        res.render("performance", {results: app.get("/api/notifications", function (request, response) {return response.body;}), title: "Performance"});
    });
};

/api/notifications 将返回json数据,然后在jade中使用如下:

block pageContent
    for result in results
         p #{result.message}

【问题讨论】:

    标签: express pug


    【解决方案1】:

    创建一个函数来获取通知并将它们传递给回调。然后在两条路线中使用该功能。您可以将其编码为纯函数或连接中间件。

    纯函数

    function loadNotifications(callback) {
        database.getNotificiations(callback)
    }
    
    app.get('/api/notifications', function (req, res) {
        loadNotifications(function (error, results) {
            if (error) { return res.status(500).send(error);
            res.send(results);
        }
    });
    
    app.get('/pages/performance', function (req, res) {
        loadNotifications(function (error, results) {
            if (error) { return res.status(500).send(error);
            res.render('performance', {results: results});
        });
    });
    

    中间件

    function loadNotifications(req, res, next) {
        database.getNotificiations(function (error, results) {
            if (error) { return next(error);}
            req.results = results;
            next();
        });
    }
    
    app.get('/api/notifications', loadNotifications, function (req, res) {
        res.send(req.results);
    });
    
    app.get('/pages/performance', loadNotifications, function (req, res) {
        res.render('performance', {results: req.results});
    });
    

    【讨论】:

    • 对 /api/notifications 的调用路由到一个服务方法,该方法又调用一个 rest util 方法。 rest util 方法调用服务层公开的 rest API 并执行“response.send(responseBody);”所以我不确定我将如何在我的情况下使用 loadNotifications 感谢您的快速响应
    • 您需要重构并提取一个函数,该函数完成/api/notifications 所做的主要工作,但不发送响应。然后你可以在两个路由中重复使用这个函数。
    猜你喜欢
    • 2022-12-11
    • 2018-08-04
    • 1970-01-01
    • 2020-10-20
    • 1970-01-01
    • 1970-01-01
    • 2018-05-30
    • 2014-04-12
    • 1970-01-01
    相关资源
    最近更新 更多