栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

从快速中间件排除路由

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

从快速中间件排除路由

即使expressjs中没有内置的中间件过滤器系统,您也可以通过至少两种方法来实现。

第一种方法是将所有要跳过的中间件(包括否定查找)挂载到正则表达式路径:

// Skip all middleware except rateLimiter and proxy when route is /example_routeapp.use(//((?!example_route).)*/, app_lookup);app.use(//((?!example_route).)*/, timestamp_validator);app.use(//((?!example_route).)*/, request_body);app.use(//((?!example_route).)*/, checksum_validator);app.use(rateLimiter);app.use(//((?!example_route).)*/, whitelist);app.use(proxy);

第二种方法(可能更易读和更简洁)是使用小的辅助函数包装中间件:

var unless = function(path, middleware) {    return function(req, res, next) {        if (path === req.path) { return next();        } else { return middleware(req, res, next);        }    };};app.use(unless('/example_route', app_lookup));app.use(unless('/example_route', timestamp_validator));app.use(unless('/example_route', request_body));app.use(unless('/example_route', checksum_validator));app.use(rateLimiter);app.use(unless('/example_route', whitelist));app.use(proxy);

如果您需要比简单功能更强大的路由匹配

path === req.path
,可以使用Express内部使用的path-to-
regexp模块

UPDATE:

express 4.17
req.path
-In仅返回’/’,因此请使用
req.baseUrl

var unless = function(path, middleware) {    return function(req, res, next) {        if (path === req.baseUrl) { return next();        } else { return middleware(req, res, next);        }    };};


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/406309.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号