如何在response.render中调用另一条快速路线。以下是我的代码段。我想在请求/ pages / performance时渲染performance.jade并使用从/ api / notifications
返回的数据填充jademodule.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}
答案 0 :(得分:0)
创建一个获取通知并将其传递给回调的函数。然后在两个路由中使用该功能。您可以将其编码为纯函数或连接中间件。
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});
});