node.js 在 ExpressJS 中为特定路由链接多个中间件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31928417/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 19:13:56  来源:igfitidea点击:

Chaining multiple pieces of middleware for specific route in ExpressJS

node.jsexpressmiddleware

提问by Anthony

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).

我只想验证一些东西,但无法在 Express 文档或在线中找到任何关于此的内容(尽管我知道这是一个功能)。

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');
});

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.

这些是无限可链的吗?如果我愿意,我可以在给定的路由上粘贴 10 个中间件函数吗?我想查看 app.get 可以接受的参数,但如前所述我在文档中找不到它。

采纳答案by robertklep

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

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

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

...

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.

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

...

您可以提供多个回调,并且所有回调都被平等对待,并且行为就像中间件,除了这些回调可能会调用 next('route') 来绕过剩余的路由回调。您可以使用此机制在路由上执行先决条件,然后在没有理由继续匹配的路由时将控制权传递给后续路由。

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).

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

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

有 10 个应该不是问题(如果你真的需要的话)。

回答by Ankur Soni

Consider following example:

考虑以下示例:

var middleware = {
    requireAuthentication: function(req, res, next) {
        console.log('private route list!');
        next();
    },
    logger: function(req, res, next) {
       console.log('Original request hit : '+req.originalUrl);
       next();
    }
}

Now you can add multiple middleware using the following code:

现在您可以使用以下代码添加多个中间件:

app.get('/', [middleware.requireAuthentication, middleware.logger], function(req, res) {
    res.send('Hello!');
});

So, from above piece of code, you can see that "requireAuthentication" and "logger" are two different middlewares added.

因此,从上面的代码段中,您可以看到“requireAuthentication”和“logger”是添加的两个不同的中间件。

回答by Lord

Express version "express": "^4.17.1" or above

快递版本“快递”:“^4.17.1”或以上

From the document: Series of Middleware

来自文档:中间件系列

var r1 = express.Router();
r1.get('/', function (req, res, next) {
  next();
});

var r2 = express.Router();
r2.get('/', function (req, res, next) {
  next();
});

app.use(r1, r2);

Let's try a real life example:

让我们尝试一个现实生活中的例子:

tourController.js

游览控制器.js

 exports.checkBody = (req, res, next)=>{ // middleware 1
    if (!req.body.price){
        return res.status(400).json({
            status:'fail',
            message:'Missing price!!!'
        })
    }
    next();
  }

 exports.createTour = (req, res) => { // middleware 2
    tours.push(req.body);
    fs.writeFile(
      `${__dirname}/dev-data/data/tours-simple.json`,
      JSON.stringify(tours),
      (err) => {
        res.status(201).json({
          status: 'success',
          data: {
            tour: newTour,
          },
        });
      }
    );
  };

tourRouter.js

TourRouter.js

const express = require('express');
const tourController = require('./../controller/tourController')
const router = express.Router();

router.route('/')
.get(tourController.getAllTours)
.post(tourController.checkBody, tourController.createTour); 
//muliple Middleware in post route

app.js

应用程序.js

const express = require('express');
const tourRouter = require('./route/tourRouter');
const app = express();

app.use(express.json());
app.use('/api/v1/tours', tourRouter);
module.exports = app;