FED

©FrontEndDev.org
2015 - 2024
web@2.22.0 api@2.20.0

Node填坑教程6:过滤器

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

比如有如下路由

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

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

app.use(function (req, res, next) {
    return res.send('filter');
});

app.get('/', function (req, res, next) {
    res.send('index');
});
```
现在不管访问什么都只能得到 filter。然后我们放过根目录的请求。

```
app.use(function (req, res, next) {
    if (req.path === '/') return next();
    return res.send('filter');
});

app.get('/', function (req, res, next) {
    res.send('index');
});
```
现在根目录能正常访问了。其他的路径仍然会显示 filter。当然根据具体逻辑能实现各种规则匹配策略。

过滤器相当于前置工作,那么与之相对的也有后置工作。通常用来处理404和错误页面。
```
app.use(function (req, res, next) {
    if (req.path === '/') return next();
    return next();
});

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

app.use(function (req, res, next) {
   res.send('404');
});
```
前置路由全部放行,根路径会匹配到get的路由,其他路径只能匹配到最后一个路由,也就是404的路由了。

那怎么显示异常页面呢,路由的回调里还有个参数,4个参数的函数会用来处理错误。
```
app.use(function (req, res, next) {
    if (req.path === '/') return next();
    return next(new Error());
});

app.get('/', function (req, res, next) {
    res.send('index');
});
 
app.use(function (req, res, next) {
   res.send('404');
});

app.use(function (err, req, res, next) {
    res.send('err');
});
```
next带上一个参数就会匹配到4个参数的路由,也就是错误处理路由了。这样非根目录的请求直接跳转到错误页面。