express路由与中间件(4)

var express = require('express'); var app = express(); var router = express.Router(); // simple logger for this router's requests // all requests to this router will first hit this middleware router.use(function(req, res, next) { console.log('%s %s %s', req.method, req.url, req.path); next(); }); // this will only be invoked if the path ends in /bar router.use('/bar', function(req, res, next) { // ... maybe some additional /bar logging ... next(); }); // always invoked router.use(function(req, res, next) { res.send('Hello World'); }); app.use('/foo', router); app.listen(3000);

router的路由必须通过app.use和app.verbs 挂载到app上才能被响应。所以上述代码,只有在app捕捉到 /foo路径上的路由时,才能router中定义的路由,虽然router中有针对 'https://www.jb51.net/' 的路由,但是被app中的路由给覆盖了。

附:app.verbs和app.use的路由路径区别:

先看一段测试代码:

var express = require('express'); var app = express(); var router = express.Router(); app.get('https://www.jb51.net/', function(req, res){ console.log('test1'); }); app.use('https://www.jb51.net/', function(req, res){ console.log('test2'); }); router.get('https://www.jb51.net/', function(req, res){ console.log('test3'); }); app.listen(4000);

输入url: localhost:4000

输出结果:test1 

输入url: localhost:4000/hello

输出结果:test2

结论:app.get挂载‘/'的路由只响应跟'https://www.jb51.net/'精确匹配的GET请求。 而app.use挂载的'https://www.jb51.net/'的路由响应所有以'https://www.jb51.net/' 为起始路由的路由,且不限制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.

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wwyssp.html