首页 > 代码库 > express 框架之 路由

express 框架之 路由

先看一段测试代码:

技术分享
 1 var express = require(‘express‘); 2  3 var app = express(); 4 var router = express.Router(); 5  6 app.get(‘/‘, function(req, res){ 7      console.log(‘test1‘); 8 }); 9 10 app.use(‘/‘, function(req, res){11      console.log(‘test2‘);12 });13 14 router.get(‘/‘, function(req, res){15      console.log(‘test3‘);16 });17 18 app.listen(4000);
View Code

输入url: localhost:4000

输出结果:test1
 
输入url: localhost:4000/hello
输出结果:test2
 
  结论:app.get挂载‘/’的路由只响应跟‘/‘精确匹配的GET请求。 而app.use挂载的‘/‘的路由响应所有以‘/‘ 为起始路由的路由,且不限制HTTP访问的方法。以下说明:Mounting a middleware at a path will cause the middleware function to be executed whenever the base of the requested path matches the path.
 
1 app.use([path], [function...], function)2 Mount the middleware function(s) at the path. If path is not specified, it defaults to "/".3 4 Mounting a middleware at a path will cause the middleware function to be executed whenever the base of the requested path matches the path.

 

express 框架之 路由