我在我的 Node 网站的每个页面上都有这个菜单:
我使用一些自定义中间件根据每个请求填充它:
app.use(function(req, res, next) {
// find the 9 most popular technologies to show in the 'technologies' menu
// drop-down. this data is needed on every page, hence the middleware.
var query =
'select \
t.technologyName, \
count(*) as count \
from technologies t \
join technology_video_map m \
on m.technologyName = t.technologyName \
where t.technologyName in ( \
select technologyName \
from technology_video_map m \
join videos v \
on m.videoId = v.videoId \
where v.approved = 1) \
group by t.technologyName \
order by count desc, t.technologyName desc \
limit 9';
connection.query(query, function(err, technologies) {
if (technologies.length === 9) {
// 'Other' is a special technology
technologies.push({ technologyName:'Other' });
}
res.locals.technologies = technologies;
next();
});
});
但是,我有返回 Json 的路由,在调用时会调用此中间件。这会导致多余的数据库调用。如何仅在返回 View 时调用此中间件?
// yes, invoke the middleware here!
router.get('/about', function(req, res) {
res.render('about');
});
// no, don't invoke the middleware here, we don't have a view!
router.get('/autocomplete', function(req, res) {
res.send({ options: new [] });
});
(我也热衷于缓存这些信息,但我会问另一个关于如何使用 node-mysql
进行缓存的问题。)
最佳答案
您可以告诉路由器仅在特定路由上调用中间件,如 Express 文档中所述 here
// will be invoked on every call to /about
router.use('/about', function(req, res, next) {
console.log('I\m such a middleware');
next();
});
// will be invoked on every call to /json/...
router.use('/json/:somejson', function(req, res, next) {
console.log('json comin..');
next();
});
// yes, invoke the middleware here!
router.get('/about', function(req, res) {
res.render('about');
});
// no, don't invoke the middleware here, we don't have a view!
router.get('/json/autocomplete', function(req, res) {
res.send({ options: new [] });
});
例如,我会分段我的路由并仅在调用 `/view/..' 时调用 db 中间件..
关于node.js - 如何有选择地调用中间件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29938831/