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

我想只是验证一些东西,但还没有能够找到任何东西在快递文档或在线关于这一点(虽然我知道这是一个功能)。

我可以只是测试了这一点,但我真的没有一个很好的模板,并希望听到从社区。

如果我这样定义一条路线:

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

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

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


app.get('/', middleware)

但是,我也可以链接至少其中一个路由来运行额外的中间件,比如身份验证,比如:

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

这些是无限链接的吗?如果我想的话,我可以在给定的路由上添加10个中间件函数吗?我想看看 app.get 可以接受的参数,但是正如前面提到的,我在文档中找不到它。

100777 次浏览

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.

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

Consider following example:

const 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 the above piece of code, you can see that requireAuthentication and logger are two different middlewares added.

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

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

 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

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


module.exports = router //need this or the following step will break

app.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;