从快递中间件中排除路由
我有一个节点应用程序坐在像其他微服务面前的防火墙/调度程序,它使用如下所示的中间件链:
... app.use app_lookup app.use timestamp_validator app.use request_body app.use checksum_validator app.use rateLimiter app.use whitelist app.use proxy ...
但是对于特定的GET路由,我想跳过除rateLimiter和proxy之外的所有路由。 他们的方式来设置一个像Rails before_filterfilter使用:except /:only?
尽pipeexpressjs中没有内置的中间件filter系统,但至less可以通过两种方式实现。
第一种方法是将所有要跳过的中间件装入正则expression式path,而不是包含负面查找:
// Skip all middleware except rateLimiter and proxy when route is /example_route app.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
更强大的路由匹配function,则可以使用Express内部使用的path-to-regexp模块 。
您也可以通过在req.originalUrl上添加条件来跳过这样的路由:
app.use(function (req, res, next) { if (req.originalUrl === '/api/login') { return next(); } else { //DO SOMETHING }
我用这个正则expression式成功:/ /^\/(?!path1|pathn).*$/
.* /^\/(?!path1|pathn).*$/
。
你可以像下面那样定义一些路线。
app.use(/\/((?!route1|route2).)*/, (req, res, next) => { //A personal middleware //code next();//Will call the app.get(), app.post() or other });