美文网首页
路由:重点

路由:重点

作者: coffee1949 | 来源:发表于2019-06-23 13:34 被阅读0次

    文档: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)
    

    相关文章

      网友评论

          本文标题:路由:重点

          本文链接:https://www.haomeiwen.com/subject/kjneqctx.html