文章目录
1 基于字符串的路由路径匹配
express的匹配规则类似于正则表达式
1.1 “?” 匹配前面字符或子字符串0或1次
如下示例,可匹配 acd
或 abcd
。
app.get('/ab?cd', function (req, res) {
res.send('ab?cd')
})
1.2 “+” 匹配前面字符或子字符串1或多次
如下示例,可匹配 abcd
、 abbcd
、abbbcd
等等。
app.get('/ab+cd', function (req, res) {
res.send('ab+cd')
})
1.3 “*” 匹配任意多字符(包括空字符)
如下示例,可匹配 abcd
、 abxcd
、 abABCDcd
、ab666cd
。
app.get('/ab*cd', function (req, res) {
res.send('ab*cd')
})
1.4 “()” 子字符串
"()"
的用处把如 ?
和 +
等匹配规则应用到一些字符上。如下示例,可匹配 abe
和 abcde
。
app.get('/ab(cd)?e', function (req, res) {
res.send('ab(cd)?e')
})
1.5 正则表达式匹配
如下示例,匹配 a
。
app.get(/a/, function (req, res) {
res.send('/a/')
})
如下示例,匹配 butterfly
或 dragonfly
等等以fly结尾的路由路径。
app.get(/.*fly$/, function (req, res) {
res.send('/.*fly$/')
})
2 路由参数匹配
路由参数以 :
开头,后接其名称,捕获的参数会放在 req.params
中。
2.1 基本规则
如下示例
app.get('/users/:userId/books/:bookId', function (req, res) {
res.send(req.params)
})
访问的url为:http://localhost:3000/users/34/books/8989
则 req.params
为:{ “userId”: “34”, “bookId”: “8989” }
注:路由参数名称只能由 [A-Za-z0-9_] 组成
2.2 “-” 与 “.” 分割路由参数
连字符 -
与点 .
可以用于分割两个路由参数,使其使用方式变得灵活。如下示例。
Route path: /flights/:from-:to
Request URL: http://localhost:3000/flights/LAX-SFO
req.params: { "from": "LAX", "to": "SFO" }
Route path: /plantae/:genus.:species
Request URL: http://localhost:3000/plantae/Prunus.persica
req.params: { "genus": "Prunus", "species": "persica" }
2.3 “()” 给路由参数指定正则表达式
这个用于给路由参数添加限制,不符合表达式则匹配不到,如下示例。
Route path: /user/:userId(\d+)
Request URL: http://localhost:3000/user/42
req.params: {"userId": "42"}
// 注:路由规则本质上是字符串,所以需要转义反斜杠
app.get('/user/:userId(\\d+)', function (req, res) {
res.send(req.params);
})
3 传递多个回调函数
如下,这是一个最基本的路由,只有一个回调函数。
app.get('/example/a', function (req, res) {
res.send('Hello from A!')
})
假如我们需要添加一个函数作为中间件对请求进行预处理,我们需要在非最后一个回调函数中添加第三个参数 next
,如:
app.get('/example/b', function (req, res, next) {
console.log('the response will be sent by the next function ...')
next()
}, function (req, res) {
res.send('Hello from B!')
})
回调函数数组示例:
var cb0 = function (req, res, next) {
console.log('CB0')
next()
}
var cb1 = function (req, res, next) {
console.log('CB1')
next()
}
var cb2 = function (req, res) {
res.send('Hello from C!')
}
app.get('/example/c', [cb0, cb1, cb2])
独立回调函数与回调函数数组可以共同使用:
var cb0 = function (req, res, next) {
console.log('CB0')
next()
}
var cb1 = function (req, res, next) {
console.log('CB1')
next()
}
app.get('/example/d', [cb0, cb1], function (req, res, next) {
console.log('the response will be sent by the next function ...')
next()
}, function (req, res) {
res.send('Hello from D!')
})