即使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); } };};


