express4.x 路由中间件

路由中间件必须通过app挂载到对应的路由上,如:

 1 var express = require('express');
 2 
 3 var router = express.Router();
 4 
 5 var app = express();
 6 
 7 app.use('/test',router); //将router路由挂载到/test路径上
 8 
 9 //将router中间件栈挂载到/test/xxx路径上,所有匹配该路径的都会执行这个中间件栈
10 router.use('/:id',function(req,res,next){
11      console.log('测试路由中间价');
12      next();//跳转到下个中间栈
13 },function(req,res){
14     res.send("这是中间件栈的第二个中间件,由它处理请求响应")
15 });
16 
17 //可以配合get方法使用
18 router.get('/',function(req,res){
19   res.send("如果请求路径为localhost:3000/test,由这个中间件处理,如果是localhost:3000/test/123这种url的话则由上面router.use绑定的中间件处理")
20 })
原文地址:https://www.cnblogs.com/toward-the-sun/p/6265033.html