如何有选择地调用中间件?

时间:2015-04-29 08:55:13

标签: node.js express node-mysql

我在Node网站的每个页面上都有这个菜单:

enter image description here

我使用一些自定义中间件在每个请求上填充它:

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的路由,在调用时会调用此中间件。这导致多余的数据库调用。如何在返回视图时调用此中间件?

// 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进行缓存的问题。)

1 个答案:

答案 0 :(得分:0)

您可以告诉路由器仅调用特定路由中的中间件,如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中间件,例如..