Express 调用app.get inside response.render
如何在response.render内调用另一个快速路由。下面是我的代码片段。我希望在请求/pages/performance时呈现performance.jade,并使用从/api/notifications返回的数据填充jadeExpress 调用app.get inside response.render,express,pug,Express,Pug,如何在response.render内调用另一个快速路由。下面是我的代码片段。我希望在请求/pages/performance时呈现performance.jade,并使用从/api/notifications返回的数据填充jade module.exports = function(app){ app.get('/pages/performance', function(req, res){ res.render("performance", {results: app
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/通知将返回json数据,然后在jade中使用,如下所示:
block pageContent
for result in results
p #{result.message}
生成一个函数,用于获取通知并将其传递给回调。然后在两条路线中使用该功能。您可以将其编码为纯函数或连接中间件 纯函数 中间件
对/api/notifications的调用路由到一个服务方法,该服务方法反过来调用一个rest-util方法。rest util方法调用服务层公开的rest API,并执行“response.send(responseBody);”因此,我不确定如何在我的案例中使用loadNotifications感谢您的快速响应您需要重构和提取一个函数,该函数完成了
/api/notifications
所做但不发送响应的主要工作。然后您可以在两条路线中重复使用此功能。
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});
});