子路由

birds.js在app目录中创建一个名为以下内容的路由器文件:

  1. var express = require('express')
  2. var router = express.Router()
  3. // middleware that is specific to this router
  4. router.use(function timeLog (req, res, next) {
  5. console.log('Time: ', Date.now())
  6. next()
  7. })
  8. // define the home page route
  9. router.get('/', function (req, res) {
  10. res.send('Birds home page')
  11. })
  12. // define the about route
  13. router.get('/about', function (req, res) {
  14. res.send('About birds')
  15. })
  16. module.exports = router

然后,在应用程序中加载路由器模块:

  1. var birds = require('./birds')
  2. // ...
  3. app.use('/birds', birds)

该应用程序现在将能够处理对/birds和的请求/birds/about,以及调用timeLog特定于该路线的中间件功能。