中间件其实也是get和post等的匹配
如果我的的get、post回调函数中,没有next参数,那么就匹配上第一个路由,就不会往下匹配了。
如果想往下匹配的话,那么需要写next() 如果没有next则无法匹配到下一个
1 app.get("/",function(req,res,next){ 2 console.log("1"); 3 next(); 4 }); 5 6 app.get("/",function(req,res){ 7 console.log("2"); 8 });
下面两个路由,感觉没有关系:
1 app.get("/:username/:id",function(req,res){ 2 console.log("1"); 3 res.send("用户信息" + req.params.username); 4 }); 5 6 app.get("/admin/login",function(req,res){ 7 console.log("2"); 8 res.send("管理员登录"); 9 });
但是实际上冲突了,因为admin可以当做用户名 login可以当做id。
解决方法1:交换位置。 也就是说,express中所有的路由(中间件)的顺序至关重要。
匹配上第一个,就不会往下匹配了。 具体的往上写,抽象的往下写。
1 app.get("/admin/login",function(req,res){ 2 console.log("2"); 3 res.send("管理员登录"); 4 }); 5 6 app.get("/:username/:id",function(req,res){ 7 console.log("1"); 8 res.send("用户信息" + req.params.username); 9 });
解决方法2:
1 app.get("/:username/:id",function(req,res,next){ 2 var username = req.params.username; 3 //检索数据库,如果username不存在,那么next() 4 if(检索数据库){ 5 console.log("1"); 6 res.send("用户信息"); 7 }else{ 8 next(); 9 } 10 }); 11 12 app.get("/admin/login",function(req,res){ 13 console.log("2"); 14 res.send("管理员登录"); 15 });
路由get、post这些东西,就是中间件,中间件讲究顺序,匹配上第一个之后,就不会往后匹配了。next函数才能够继续往后匹配。 所以我们在参数新增next,用来继续匹配其他内容!
中间件实则就是这些post用于解决冲突来解决的一种办法,下面一篇我们使用use来讲述另外一个中间件!
本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。
我来说两句