<!--
 * @Author: your name
 * @Date: 2021-08-19 14:56:43
 * @LastEditTime: 2021-08-20 11:30:59
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \md-\koa\koa使用技巧.md
-->
# koa使用技巧
## koa路由相关
### 使用koa来手动实现路由
#### 不想写,太麻烦
### 使用`koa-router`模块进行路由处理
1. **安装`koa-router`**
 
<!-- tabs:start  -->
#### **npm**
```shell
npm i koa-router --save
```
#### **yarn**
```shell
yarn add koa-router
```
<!-- tabs:end -->
2. **使用`koa-router`**
    首先导入`koa-router`,然后实例化`koa-router`,实例化时可以传入参数[`option`]类型为`Object`,`option`可以去[githob仓库](https://github.com/ZijianHe/koa-router)进行查询。
    其中 `option.prefix` 为路由前缀
    在根目录下的`app.js`文件中写入下面代码块内容.
    ```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`来运行服务.
    ```shell
    node app.js
    ```
    > [!tip]
    > 在浏览器中访问 [http://localhost:3000](http://localhost:3000) 可以看见一个`hello World` ,表示路由使用成功
    
    **使用路由前缀**
    `koa-router`中设置路由前缀,比如用户模块下的路由为`/home/xx`形式.可以通过路由前缀来分模块写路由
    在`koa-router`中路由前缀在实例化路由时用参数 `prefix`来进行设置
    编辑`app.js`文件
    ```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](http://localhost:3000/home/question) 可以看见一个`没人在家`,表示路由前缀设置成功