Route 路由

基础使用

const express = require('express')
const app = express()
const bodyParser = require('body-parser');
const port = 7890

const user = [
  { name: 'LiLei', sex: 'male', age: '18' },
  { name: 'Lucy', sex: 'female', age: '18' }
]

// 处理典型的中间件
app.use(bodyParser.json());                         // for parsing application/json
app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded

app.get('/user', (req, res) => {    // 获取列表
  res.send(user)
})

app.post('/user', (req, res) => {   // 添加
  user.push(req.body)
  res.send(user)
})

app.put('/user', (req, res) => {  // 修改
  debug('body: %o', req.body)
  let index = user.findIndex(item => {
    return item.name === req.body.name
  })

  index >=0 ? user[index] = req.body : user.push(req.body)
  res.send(user)
})

app.delete('/user', (req, res) => { // 删除
  debug('body: %o', req.body)
  let index = user.findIndex(item => {
    return item.name === req.body.name
  })
  user.splice(index, 1)
  res.send(user)
})

app.all('/user', (req, res) => {
  // do sth
})

路由的正则匹配参照

  • 这一部分,Express是使用path-to-regexp来匹配路由串
  • 像这样的使用,在React``Vue等前端框架上都有体现
app.get('/ab*ef', callback)       // 匹配 abxxxxxef abxef

app.get('/ab?cd', callback)       // 匹配 abcd abd

app.get('/ab+cd', callback)       // 匹配 abbbbbcd abbcd

app.get('/ab(cd)?ef', callback)   // abef 或 abcdef

app.get(/.*fly$/, cb)             // 不赘述

路由带参

app.get('/users/:userId/books/:bookId', function (req, res) {
  res.send(req.params)    // req.params.userId/req.params.bookId
})

app.get('/flights/:from-:to', function (req, res) {
  // /flights/guangZ-beiJ
  res.send(req.params)    // req.params.userId/req.params.bookId
})

app.get('/location/:province.:city', function (req, res) {
  // /location/GuangD.GuangZ
  res.send(req.params)    // req.params.userId/req.params.bookId
})

多级回调来灵活处理请求

app.get('/example/b', function (req, res, next) {
  console.log('the response will be sent by the next function ...')
  // do sth here
  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])
// or
app.get('/example/c', [cb0, cb1, cb2], () => {}, () => { res.send() })

使用app.route()链式构建路由结构

app.route('/user(/:id)?')
  .get(function (req, res) {
    let id = req.params.id
    if (id) {
      // return user[id]
    } else {
      // return all users : res.send(users)
    }
  })
  .post(function (req, res) {
    // push req.body.theContent to users
    res.send('post success')
  })
  .delete((req, res => {
    let id = req.params.id
    if (id) {
      // do delete id
    } else {
      // do nothing
    }
  }))

使用express.Router类实例化router对象,并像中间件一样使用他们

  • 这种方法看起来会更灵活
  • 不过,实际上还是要根据不同的情况去使用
// bird.js

// 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

// route.js
const routeBird = require('./bird')
app.use('/bird', routeBird)

results matching ""

    No results matching ""