路由:重点

2019-06-23  本文已影响0人  coffee1949

文档:http://expressjs.com/en/4x/api.html#router

一:app.get()

// GET method route
app.get('/', function (req, res) {
  res.send('GET request to the homepage')
})

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

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!')
})

二:app.post()

// POST method route
app.post('/', function (req, res) {
  res.send('POST request to the homepage')
})

三:app.all()

app.all('/secret', function (req, res, next) {
  console.log('Accessing the secret section ...')
  next() // pass control to the next handler
})

四: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

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
var userRouter= require('./routes/index')

// ...

app.use('/user', userRouter)
上一篇下一篇

猜你喜欢

热点阅读