koa请求参数验证middlware
发布于 5 年前 作者 4074 6138 次浏览 来自 分享

先上 github 地址 koa-proper

最近写node服务端写多了,每个接口都要进行参数验证。 重复代码很多,所以抽象了一个中间件。

功能:

  • 对参数对象进行类型验证,基于 prop-types (一个react衍生的类型定义库)
  • 验证失败自动抛出 http 400 错误 (可关闭,可自定义)

使用简单,功能实用,话不多说看代码:

import Koa from 'koa'
import proper from 'koa-proper'

const app = new Koa()
app.use(proper())

app.use(async ctx => {
    // 请求参数: {string: any}
    const props = ctx.request.query
    // 定义参数类型: {string: PropType}
    // ctx.PropTypes 就是 prop-types
    const types = {
        username: ctx.PropTypes.string.isRequired
    }

    // ctx.proper 为验证方法
    // 如果验证通过,返回原数据
    const params = ctx.proper(props, types)

    // 如果失败, 会自动抛出 http error 
    // 可以在 options 里关闭或者自定义

    // ctx.throw(400, error) <---- 默认的错误抛出方法

    // 验证通过才会执行下面代码
    ctx.body = params
})

再上 github 地址 koa-proper

3 回复

参数校验最好在路由层面做,我们是把 koa-router 改了:https://cnodejs.org/topic/5c7f48af5b8cb21491ca65d0

@helloyou2012 不错不错!

回到顶部