koa使用技巧.md 2.4 KB

koa使用技巧

koa路由相关

使用koa来手动实现路由

不想写,太麻烦

使用koa-router模块进行路由处理

  1. 安装koa-router

npm

npm i koa-router --save

yarn

yarn add koa-router
  1. 使用koa-router 首先导入koa-router,然后实例化koa-router,实例化时可以传入参数[option]类型为Object,option可以去githob仓库进行查询。 其中 option.prefix 为路由前缀 在根目录下的app.js文件中写入下面代码块内容.

    const Koa = require('koa')
    const Router = require('koa-router')
    
    const app = new Koa()
    const router = new Router()
    
    router.get('/',async ctx=>{
        ctx.body = 'Hello World'
    })
    
    app.use(router.routes()).use(router.allowedMethods())
    app.listen(3000)
    
    

    编辑完app.js后,在终端中用node来运行服务.

    node app.js
    

    [!tip] 在浏览器中访问 http://localhost:3000 可以看见一个hello World ,表示路由使用成功

    使用路由前缀 koa-router中设置路由前缀,比如用户模块下的路由为/home/xx形式.可以通过路由前缀来分模块写路由 在koa-router中路由前缀在实例化路由时用参数 prefix来进行设置 编辑app.js文件

        const Koa = require('koa')
        const Router = require('koa-router')
    
        const app = new Koa()
        // 传入option,设置prefix的值为home
        const router = new Router({
            prefix: '/home'
        })
    
        router.get('/',async ctx=>{
            ctx.body = 'welcome to my home'
        })
        router.get('/question',async ctx=>{
            ctx.body = '没人在家'
        })
    
        app.use(router.routes()).use(router.allowedMethods())
        app.listen(3000)
    

    重新运行app.js

    [!tip] 在浏览器中访问 http://localhost:3000/home/question 可以看见一个没人在家,表示路由前缀设置成功