node.js - 如何有选择地调用中间件?

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

相关文章:

javascript - 当所有参数都是可选的时,如何向 Node.js 中的 Web 服务 GET 方法添加验证?

node.js - 缩进无效。 Jade 模板

Node.Js/Express - 输出响应的前几个字符的简单中间件

javascript - 在 node.js mysql 查询中,检查是否没有找到匹配项

node.js - 是否可以使用许多函数(超过 10 个)来处理 Node 的异步特性(尤其是添加到 MySql 数据库时)

javascript - Node : Express. 如何延迟响应?

node.js - 意外的 token 非法 - Istanbul 尔测试_mocha

node.js - 发布请求的 "Body"始终采用 unicode

javascript - Rethinkdb 使用 thinky 更改 Express.js 中的 feed

javascript - 如何以非纯文本形式存储我的 Node mysql 密码?