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

查看:42
本文介绍了在 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.

如果我像这样在 express 中定义路由:

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:

...

你可以提供多个回调,并且所有回调都被平等对待,就像中间件一样,只是这些回调可能会调用 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天全站免登陆