美文网首页
使用koa-parameter校验参数

使用koa-parameter校验参数

作者: HuFan_JS | 来源:发表于2020-03-26 22:02 被阅读0次

下载

npm i koa-parameter

注册

const parameter  = require('koa-parameter')

挂载

//放在请求体后面,因为是用来校验请求体参数
// 传入app,因为可以在ctx中加入一个方法,这样可以让我们全局校验
app.use(parameter(app))

使用示例

  updateById(ctx) {
    ctx.verifyParams({
      name: { type: 'string', required: true },
      age: { type: 'number', required: false }
    })
    let id = parseInt(ctx.params.id)
    if (id >= db.length) {
      ctx.throw(412)
    }
    db[id] = ctx.request.body
    ctx.body = db[parseInt(ctx.params.id)]
  }

结果

//若出现不符合我们定义的参数格式,会向客户端发送具体的422错误,以及具体的报错信息
{
  "message": "Validation Failed",
  "errors": [
    {
      "message": "required",
      "field": "name",
      "code": "missing_field"
    }
  ],
  "params": {
    "age": 18,
    "id": "0"
  }
}

相关文章

网友评论

      本文标题:使用koa-parameter校验参数

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