在ExpressJS中为特定路由链接多个中间件 [英] Chaining multiple pieces of middleware for specific route in ExpressJS

查看:239
本文介绍了在ExpressJS中为特定路由链接多个中间件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只想验证一下内容,但无法在Express文档或在线文档中找到与此相关的内容(尽管我知道这是一个功能).

I want to just verify something but have't been able to find anything in the Express docs or online regarding this (although I know it's a feature).

我可以对此进行测试,但是我确实没有一个很好的模板,希望听到社区的意见.

I could just test this out but I don't really have a nice template and would like to hear from the community.

如果我这样定义快递路线:

If I define a route in express like such:

app.get('/', function (req, res) {
  res.send('GET request to homepage');
});

我还可以定义一个中间件并直接加载,例如

I can also define a middleware and load it directly, such as

middleware = function(req, res){
  res.send('GET request to homepage');
});

app.get('/', middleware)

但是,我也可以将这些路由中的至少一条链接起来,以运行额外的中间件,例如身份验证,如下所示:

However, I can also chain at least one of these routes to run extra middleware, such as authentication, as such:

app.get('/', middleware, function (req, res) {
  res.send('GET request to homepage');
});

这些是无限可链接的吗?如果愿意,可以在给定的路由上添加10个中间件功能吗?我想查看app.get可以接受的参数,但是就像提到的那样,我在文档中找不到它.

Are these infinitely chainable? Could I stick 10 middleware functions on a given route if I wanted to? I want to see the parameters that app.get can accept but like mentioned I can't find it in the docs.

推荐答案

不是说无限",而是说您可以添加多个中间件功能(在文档中称为回调" )此处:

It's not saying "infinitely", but it does say that you can add multiple middleware functions (called "callbacks" in the documentation) here:

router.METHOD(路径,[回调,...]回调)

...

router.METHOD(path, [callback, ...] callback)

...

您可以提供多个回调,并且所有回调均被平等对待,并且行为与中间件类似,不同的是这些回调可以调用next('route')绕过其余的路由回调.您可以使用这种机制对路由执行先决条件,然后在没有理由继续进行匹配的路由时将控制权传递给后续路由.

You can provide multiple callbacks, and all are treated equally, and behave just like middleware, except that these callbacks may invoke next('route') to bypass the remaining route callback(s). You can use this mechanism to perform pre-conditions on a route then pass control to subsequent routes when there is no reason to proceed with the route matched.

如您所见,中间件功能和通常处理请求的功能(通常是添加到列表中的最后一个功能)之间没有区别.

As you can see, there's not distinction between a middleware function and the function that commonly handles the request (the one which is usually the last function added to the list).

拥有10个也不是问题(如果您确实需要).

Having 10 shouldn't be a problem (if you really need to).

这篇关于在ExpressJS中为特定路由链接多个中间件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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