express4.x中路由中间件和挂载路径的关系

时间:2022-02-10 09:38:14

express4.x 中一个路由中间件可以挂载到多个路由上,一个路由也可以绑定多个路由中间件,如:

 //多个路由匹配一个路由中间件
app.use(['/gre+t', '/hel{2}o'], greet); var greet = express.Router(); greet.get('/jp', function (req, res) {
console.log(req.baseUrl); // /greet
res.send('Konichiwa!');
}); app.use('/greet', greet); //多个中间件匹配一个路由
app.use('/rtest', [r1, r2]); var r1 = express.Router();
r1.get('/', function (req, res, next) {
console.log("r1 router");
next();
}) var r2 = express.Router();
r2.get('/', function (req, res, next) {
console.log('r2 router ');
res.send("r2 router " + req.app.get("view engine"))
// next();
})