koa-router的基本使用

koa-router的基本使用

1.作用

Router middleware for koa

2.提供的功能
  • Express-style routing using app.get, app.put, app.post, etc.
  • Named URL parameters.
  • Named routes with URL generation.
  • Responds to OPTIONS requests with allowed methods.
  • Support for 405 Method Not Allowed and 501 Not Implemented.
  • Multiple route middleware.
  • Multiple routers.
  • Nestable routers.
  • ES7 async/await support.
3.在koa项目中的使用

// index.js

const Koa = require('koa');
    const Router = require('koa-router');
    const koaBodyparser  = require('koa-bodyparser');
    const app = new Koa();
    const router = new Router();
    const book = require('../routes/book')
    
    //中间件按照写的顺序执行的
    app.use(koaBodyparser())
    //router.use(path:string,middleware:method)
    router.use('/api', book.routes());

// routes/bookController

    const bookAPI = require('../controllers/EBookController.js');
    const koaRouter = require('koa-router');
    
    const router = koaRouter()
    
    router.get('/book/:id', bookAPI.getBook);
    router.get('/book', bookAPI.getBookByCategory)
    router.post('/book/:id/create', bookAPI.createBook)
    router.post('/book/:id/delete', bookAPI.removeBook)
    router.post('/book/:id/update', bookAPI.updateBook)
    
    module.exports = router;

当路由跳转到 http://localhost:8080/api/book...的时候,将会调用bookAPI中对应的controller进行响应

再次说明

router.use(path1,middleware)中的path 将会和routes中的router.get(path2)嵌套作用 ,即路由转到 path1/path2 时会由相应的控制器响应。

你可能感兴趣的:(koa-router的基本使用)