express中app.use的使用

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');
})

路径可以用一个字符串,一个模式,一个正则表达式来表示或者他们的组合形式。例如:

TypeExample
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();
})

未完待续。。。

  • 4
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值