Node填坑教程——过滤器

所谓“过滤器”,只是一个概念,可以理解是一个路由,也可以理解为一个中间件。原理非常简单,就是利用匹配规则,让其有限匹配在正常的路由前面处理就行了。

比如有如下路由

1 app.get('/', function (req, res, next) {
2     res.send('index');
3 });

访问根目录就能看到index。在前面加上一个路由,封锁全部请求

1 app.use(function (req, res, next) {
2     return res.send('filter');
3 });
4 
5 app.get('/', function (req, res, next) {
6     res.send('index');
7 });

现在不管访问什么都只能得到 filter。然后我们放过根目录的请求。

1 app.use(function (req, res, next) {
2     if (req.path === '/') return next();
3     return res.send('filter');
4 });
5 
6 app.get('/', function (req, res, next) {
7     res.send('index');
8 });

现在根目录能正常访问了。其他的路径仍然会显示 filter。当然根据具体逻辑能实现各种规则匹配策略。

过滤器相当于前置工作,那么与之相对的也有后置工作。通常用来处理404和错误页面。

 1 app.use(function (req, res, next) {
 2     if (req.path === '/') return next();
 3     return next();
 4 });
 5 
 6 app.get('/', function (req, res, next) {
 7     res.send('index');
 8 });
 9 
10 app.use(function (req, res, next) {
11    res.send('404');
12 });

前置路由全部放行,根路径会匹配到get的路由,其他路径只能匹配到最后一个路由,也就是404的路由了。

那怎么显示异常页面呢,路由的回调里还有个参数,4个参数的函数会用来处理错误。

 1 app.use(function (req, res, next) {
 2     if (req.path === '/') return next();
 3     return next(new Error());
 4 });
 5 
 6 app.get('/', function (req, res, next) {
 7     res.send('index');
 8 });
 9 
10 app.use(function (req, res, next) {
11    res.send('404');
12 });
13 
14 app.use(function (err, req, res, next) {
15     res.send('err');
16 });

next带上一个参数就会匹配到4个参数的路由,也就是错误处理路由了。这样非根目录的请求直接跳转到错误页面。

posted @ 2015-05-08 11:23  小鹭  阅读(1671)  评论(0编辑  收藏  举报