从快速中间件排除路由 [英] Exclude route from express middleware

查看:508
本文介绍了从快速中间件排除路由的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个节点应用程序就像防火墙/调度程序在其他微服务前面,它使用一个中间件链,如下所示:

I have a node app sitting like a firewall/dispatcher in front of other micro services and it uses a middleware chain like below:

...
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_filter使用:except /:only?

However for a particular GET route I want to skip all of them except rateLimiter and proxy. Is their a way to set a filter like a Rails before_filter using :except/:only?

推荐答案

在expressjs中的中间件过滤系统中,您可以通过至少两种方式实现这一点。

Even though there is no build-in middleware filter system in expressjs, you can achieve this in at least two ways.

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

First method is to mount all middlewares that you want to skip to a regular expression path than includes a negative lookup:

// 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);

第二种方法,可能更可读和更干净一个,是用一个小助手函数包装你的中间件:

Second method, probably more readable and cleaner one, is to wrap your middleware with a small helper function:

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内部使用的路径到正则表达式模块

If you need more powerfull route matching than simple path === req.path you can use path-to-regexp module that is used internally by Express.

这篇关于从快速中间件排除路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆