路由处理程序

中英双语

您可以提供多个回调函数,其行为类似于 中间件 来处理请求。唯一的例外是这些回调可能会调用 next('route') 来绕过剩余的路由回调。您可以使用此机制对路由施加先决条件,然后如果没有理由继续当前路由,则将控制权传递给后续路由。

路由处理程序的形式可以是函数、函数数组或两者的组合,如以下示例所示。

单个回调函数可以处理路由。例如:

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

一个以上的回调函数可以处理一个路由(确保你指定了 next 对象)。例如:

app.get('/example/b', (req, res, next) => {
  console.log('the response will be sent by the next function ...')
  next()
}, (req, res) => {
  res.send('Hello from B!')
})

一组回调函数可以处理路由。例如:

const cb0 = function (req, res, next) {
  console.log('CB0')
  next()
}

const cb1 = function (req, res, next) {
  console.log('CB1')
  next()
}

const cb2 = function (req, res) {
  res.send('Hello from C!')
}

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

独立函数和函数数组的组合可以处理路由。例如:

const cb0 = function (req, res, next) {
  console.log('CB0')
  next()
}

const cb1 = function (req, res, next) {
  console.log('CB1')
  next()
}

app.get('/example/d', [cb0, cb1], (req, res, next) => {
  console.log('the response will be sent by the next function ...')
  next()
}, (req, res) => {
  res.send('Hello from D!')
})