zoukankan      html  css  js  c++  java
  • 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个参数的路由,也就是错误处理路由了。这样非根目录的请求直接跳转到错误页面。

  • 相关阅读:
    《算法竞赛入门经典》(刘汝佳)——排序与检索(基础)
    Python中的GIL
    MongoDB 安装
    python3 报错集合
    socket 实例化方法
    socket入门
    Day_6作业_模拟人生
    高阶函数举例
    面向对象_python
    xml
  • 原文地址:https://www.cnblogs.com/heron/p/4487166.html
Copyright © 2011-2022 走看看