基本使用

  • app.method(path,handler)
  • 每个路由可以具有 一个多个 处理程序函数,这些函数在匹配该路由时执行
// 在根路径响应 get 请求
app.get('/', (req, res) => {  res.send('Hello World!') })

// 在根路径响应 post 请求
app.post('/', (req, res) => { res.send('post /') })

// 在根路径响应 put 请求
app.put('/', (req, res) => { res.send('put /') })

// 在根路径响应 delete 请求
app.delete('/', (req, res) => { res.send('delete /') })

// 在根路径响应所有请求
app.all('/', function (req, res, next) { res.send('delete user') })

next(‘route’) 作用

从路由中间件堆栈中跳过其余中间件,将控制权传递给下一个路由(仅在 app.method() 或者 router.method() 加载的中间件函数中有效)

app.get('/user/:id',
  (req, res, next) => {
    // next('route') 跳到下一个中间件,则返回 special
    if (req.params.id === '0') next('route')
    else next()
  },
  (req, res, next) => {
    res.send('regular')
  }
)

app.get('/user/:id', (req, res, next) => {
  res.send('special')
})

路由匹配

可以是 字符串字符串模式正则表达式

字符串

// 字符串:匹配 /about
app.get('/about', (req, res) => { res.send('root') })

字符串模式

// 字符串模式:匹配 acd 和匹配 abcd
app.get('/ab?cd', (req, res) => { res.send('ab?cd') })

// 字符串模式:匹配 abcd、abbcd、abbbcd、......
app.get('/ab+cd', (req, res) => { res.send('ab?cd') })

// 字符串模式:匹配 abcd、abxcd、abRANDOMcd、ab123cd、......
app.get('/ab*cd', (req, res) => { res.send('ab*cd') })

// 字符串模式:匹配 /abe 和 /abcde
app.get('/ab(cd)?cd', (req, res) => { res.send('ab*cd') })

正则表达式

// 正则表达式:匹配 带 a 的任何内容
app.get('/a/', (req, res) => { res.send('/a/') })

路由参数

用于捕获 URL 中在其位置处指定的值,捕获的值将填充到 req.params 对象中

  1. 要使用路由参数定义路由,在路径中指定路由参数:

  2. 路径参数名称必须由文字字符 [a-zA-Z0-9] 组成,-. 按字面解析,可以将路由参数一起使用:

  3. 要路由 route 参数匹配的确切字符串,可以在括号后面附加一个正则表达式,由于正则表达式是字符串的一部分,因此使用 \ 对所有字符进行转义;

路由处理程序

单个回调函数

app.get('/example/a', (req, res) => { res.send('hello from a!') })

多个回调函数

app.get("/example/b",
  (req, res, next) => { next() },
  (req, res, next) => { res.send("hello from b!") }
);

回调函数数组

function cb0(req, res, next) {
  console.log('cb0')
  next()
}
function cb1(req, res, next) {
  console.log('cb1')
  next()
}
function cb2(req, res, next) {
  res.send('"hello from c!')
}

app.get('/example/c', [cb0, cb1, cb2])

单个回调函数和函数数组组合

function cb0(req, res, next) {
  console.log('cb0')
  next()
}
function cb1(req, res, next) {
  console.log('cb1')
  next()
}

app.get('/example/d',
  [cb0, cb1],
  (req, res, next) => { next() },
  (req, res, next) => { res.send('"hello from d!') }
)

路由中间件图解

二级路由中间件图解

打赏作者
您的打赏是我前进的动力
微信
支付宝
评论

中午好👏🏻,我是 ✍🏻   疯狂 codding 中...

粽子

这有关于前端开发的技术文档和你分享。

相信你可以在这里找到对你有用的知识和教程。

了解更多

目录

  1. 1. 基本使用
  2. 2. next(‘route’) 作用
  3. 3. 路由匹配
    1. 3.1. 字符串
    2. 3.2. 字符串模式
    3. 3.3. 正则表达式
  4. 4. 路由参数
  5. 5. 路由处理程序
    1. 5.1. 单个回调函数
    2. 5.2. 多个回调函数
    3. 5.3. 回调函数数组
    4. 5.4. 单个回调函数和函数数组组合
  6. 6. 路由中间件图解
  7. 7. 二级路由中间件图解