app.use([path,] function [, function…])
在path上安装中间件,如果path没有被设定,那么默认为”/”。
当为路由设置一个匹配路径后,路由会匹配该路径及该路径下所有的路径。例如:
app.use(‘/apple’, …)会匹配请求路径’/apple’, ‘/apple/images’,
‘/apple/images/news’等。
在中间件中req.originalUrl是req.baseUrl和req.path的组合,如下面的例子所示:
app.use('/admin', function(req, res, next) {
// GET 'http://www.example.com/admin/new'
console.log(req.originalUrl); // '/admin/new'
console.log(req.baseUrl); // '/admin'
console.log(req.path); // '/new'
next();
});
在path路径上安装中间件,每当请求的路径的基路径和该path匹配时,都会导致该中间件函数被执行。例如,默认路径’/’,即当中间件没有设置安装路径时,任何向该应用的请求都会触发该中间件函数。
// this middleware will be executed for every request to the app
app.use(function (req, res, next) {
console.log('Time: %d', Date.now());
next();
})
中间件函数是按顺序执行的,因此中间件的顺序也很重要。
// this middleware will not allow the request to go beyond it
app.use(function(req, res, next) {
res.send('Hello World');
})
// requests will never reach this route
app.get('/', function (req, res) {
res.send('Welcome');
})
路径可以用一个字符串,一个模式,一个正则表达式来表示或者他们的组合形式。例如:
Type | Example |
---|---|
Path | // will match paths starting with /abcd app.use(‘/abcd’, function (req, res, next) { next(); }) |
PathPattern | // will match paths starting with /abcd and /abd app.use(‘/abc?d’, function (req, res, next) { next(); }) // will match paths starting with /abcd, /abbcd, /abbbbbcd and so on app.use(‘/ab+cd’, function (req, res, next) { next(); }) // will match paths starting with /abcd, /abxcd, /abFOOcd, /abbArcd and so on app.use(‘/ab*cd’, function (req, res, next) { next();}) // will match paths starting with /ad and /abcd app.use(‘/a(bc)?d’, function (req, res, next) { next(); }) |
Regular Expression | // will match paths starting with /abc and /xyz app.use(/\/abc|\/xyz/, function (req, res, next) { next(); }) |
Array | // will match paths starting with /abcd, /xyza, /lmn, and /pqr app.use([‘/abcd’, ‘/xyza’, /\/lmn|\/pqr/], function (req, res, next) { next(); }) |
未完待续。。。