koa --- > koa-bouncer验证

使用 koa-bouncer中间件对传入的数据进行验证

const bouncer = require('koa-bouncer');
app.use(bouncer.middleware());

const val = async (ctx, next) => {
    ctx.validateBody('name')
    .required('要求提供用户名')
    .isLength(6, 16, '用户名长度应该为6~16')
    .isString()
    .trim()
    next();
}


router.post('/', val, ctx => {
    console.log('POST /users');
    const { body: user } = ctx.request;
    user.id = users.length + 1; // 自增
    users.push(user);
    ctx.body = {
        ok: 1
    }
});
  • 说明:
    ctx.validateBody:之所以可以使用,是因为,在上面配置了const bouncer = require('koa-bouncer')app.use(bouncer.middleware())
    在这里插入图片描述
    当提交的名字长度不在6~16时,后台会报错如下:
    在这里插入图片描述
发布了177 篇原创文章 · 获赞 22 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/piano9425/article/details/103346439
koa