美文网首页
koa2使用路由中间件

koa2使用路由中间件

作者: 夏夏夏夏顿天 | 来源:发表于2018-11-27 16:11 被阅读22次

    这篇我们来使用一个koa-router, 控制一下路由

    本篇的版本:注意版本哦

    目录结构:

    image.png

    1.编辑index.js

    const Koa = require('koa')
    const Router =  require('koa-router')
    const app = new Koa()
    
    
    // 子路由1
    const home = new Router()
    
    home.get('/', async (ctx) => {
        ctx.body = "home pages"
    })
    
    
    // 子路由2
    const page = new Router()
    
    page.get('/404', async (ctx) => {
        ctx.body = '404 pages'
    })
    
    
    const login = new Router()
    
    login.get('/', async (ctx) => {
        ctx.body = 'login pages'
    })
    
    // 装载所有子路由
    let router = new Router()
    router.use('/', home.routes(), home.allowedMethods())
    router.use('/page', page.routes(), page.allowedMethods())
    router.use('/login', login.routes(), login.allowedMethods())
    
    // 加载路由中间件
    app.use(router.routes()).use(router.allowedMethods())
    
    
    
    app.listen(3000, () => {
        console.log('localhost:3000')
    })
    

    2.启动服务,打开浏览器

    node index.js
    

    访问:localhost:3000, localhost;3000/login , localhost:3000/page/404

    都是可以看的到结果的

    image.png

    关于koa-router其他API

    源码地址:https://github.com/alexmingoia/koa-router

    router
      .get('/', (ctx, next) => {
        ctx.body = 'Hello World!';
      })
      .post('/users', (ctx, next) => {
        // ...
      })
      .put('/users/:id', (ctx, next) => {
        // ...
      })
      .del('/users/:id', (ctx, next) => {
        // ...
      })
      .all('/users/:id', (ctx, next) => {
        // ...
      });
    

    后记

    关于koa相关的路由控制中间件有很多,就看自己的选择了

    这里有个中路由中间件汇集https://cnodejs.org/topic/57838dfaee5f048d54f90877

    相关文章

      网友评论

          本文标题:koa2使用路由中间件

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