express中app.use的使用
阿新 • • 發佈:2018-11-22
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(); }) |
未完待續。。。
轉載於:https://blog.csdn.net/zhujun_xiaoxin/article/details/79030946