初始化项目

安装依赖

1
2
yarn add koa
yarn add nodemon -D

简单的Hello World

1
2
3
4
5
6
7
8
const Koa = require('koa')

const app = new Koa()

app.use((ctx) => {
ctx.body = 'Hello World'
})
app.listen(3000)

image-20201123084431088

nodemon使用了内部安装,因此需要在package.json中写运行脚本才可以使用。

1
2
3
4
5
{
"scripts": {
"server": "nodemon index.js"
}
}

路由

一个简单的判断路由路径和请求方法

1
2
3
4
5
6
7
app.use(async (ctx) => {
if (ctx.url === '/' && ctx.method == "GET") {
ctx.body = '主页'
} else {
ctx.body = '其他页面'
}
})

koa-router

安装插件

1
yarn add koa-router

简单使用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
const Koa = require('koa')
const Router = require('koa-router')
const app = new Koa()
const router = new Router()
router.get('/', (ctx) => {
ctx.body = '你好'
})
router.post('/users', (ctx) => {
ctx.body = '用户接口'
})
router.get('/users/:id', (ctx) => {
ctx.body = '用户接口' + ctx.params.id
})
app.use(router.routes())
app.listen(3000)

image-20201123090900470

如果使用前缀则在创建实例时填入参数即可

1
const router = new Router({prefix:'/api'})

多中间件

1
2
3
4
5
6
7
8
9
10
// 多中间件
const auth = async (ctx, next) => {
if (ctx.url !== '/user') {
ctx.throw(401)
}
await next()
}
router.get('/users', auth, (ctx) => {
ctx.body = '用户接口'
})

allowedMethods

此方法用于options请求

1
app.user(router.allowedMethods())

相应的可以返回405501

控制器

  1. 获取queryparmas

    ctx.queryctx.parmas

  2. 获取请求体

    • 安装插件

      1
      yarn add koa-bodyparser
    • 注册中间件

      1
      2
      const bodyparser = require('koa-bodyparser')
      app.use(bodyparser())
    • 通过ctx.request.body获取

  3. 设置响应头

    1
    ctx.set('allo','ab')

参数校验

  1. 安装插件

    1
    yarn add koa-parameter
  2. 使用

    • 入口文件注册

      1
      2
      const parameter = require('koa-parameter')
      app.use(parameter(app))
    • 控制器中使用

      1
      2
      3
      4
      5
      6
      create (ctx) {
      ctx.verifyParams({
      name: { type: 'string', required: true },
      age: { type: 'number', required: false }
      })
      }

错误处理

在入口文件添加中间件

1
2
3
4
5
6
7
8
9
10
app.use(async (ctx, next) => {
try {
await next()
} catch (err) {
ctx.status = err.status || err.statusCode || 500
ctx.body = {
message: err.message
}
}
})

使用koa-json-error中间件设置错误处理

1
yarn add koa-json-error

注册为中间件使用

1
2
3
const error = require('koa-json-error')
// 默认配置
app.use(error())

通过环境变量设置返回格式

1
2
3
4
// 默认配置
app.use(error({
postFormat: (e, { staack, ...rest }) => process.env.NODE_ENV === 'production' ? rest : { staack, ...rest }
}))