本文仅用于学习记录,不存在任何商业用途,如侵删
您可以提供多个回调函数,它们的行为类似于中间件来处理请求。
唯一的例外是这些回调可能会调用next('route')以绕过剩余的路由回调。您可以使用此机制对路由施加先决条件,然后如果没有理由继续当前路由,则将控制权传递给后续路由。
路由处理程序的形式可以是函数、函数数组或两者的组合,如以下示例所示。
单个回调函数可以处理路由。例如:
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!')
})

妙啊
下表中响应对象(res)上的方法可以向客户端发送响应,并终止请求-响应循环。
如果没有从路由处理程序调用这些方法,则客户端请求将被挂起。

解释:【谷歌翻译的…】

可以使用app.route(). 因为路径是在单个位置指定的,所以创建模块化路由是有帮助的,因为这有助于减少冗余和拼写错误。
有关路由的更多信息,请参阅:Router() 文档。
下面是一个使用app.route()的栗子.
app.route('/book')
.get(function (req, res) {
res.send('Get a random book')
})
.post(function (req, res) {
res.send('Add a book')
})
.put(function (req, res) {
res.send('Update the book')
})

重新运行服务,测试

没毛病
使用express.Router。
该类创建模块化、可安装的路由处理程序。
实例是一个Router完整的中间件和路由系统;因此,它通常被称为“迷你应用程序”。
birds.js在 app 目录下创建一个名为 router 的文件,内容如下:【这翻译的啥…】

OK,看英文看懂了…
var express = require('express')
var router = express.Router()
// middleware that is specific to this router
router.use(function timeLog (req, res, next) {
console.log('Time: ', Date.now())
next()
})
// define the home page route
router.get('/', function (req, res) {
res.send('Birds home page')
})
// define the about route
router.get('/about', function (req, res) {
res.send('About birds')
})
module.exports = router

在app.js 应用程序中加载路由模块bird.js
var birds = require('./birds')
app.use('/birds',birds)

该应用程序现在将能够处理对/birds和的请求/birds/about,以及调用timeLog特定于路由的中间件函数。
重新运行服务,测试


厉害厉害。