使用 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时,后台会报错如下: