此控件支持Josn,form,text类型
用法
var Koa = require('koa'); var bodyParser = require('koa-bodyparser'); var app = new Koa(); app.use(bodyParser()); app.use(async ctx => { // the parsed body will store in ctx.request.body // if nothing was parsed, body will be an empty object {} ctx.body = ctx.request.body; });
参数:
disableBodyParser,可以动态设置不转换
app.use(async (ctx, next) => { if (ctx.path === '/disable') ctx.disableBodyParser = true; await next(); }); app.use(bodyparser());
onerror,用户化设置转换出错时的处理
app.use(bodyparser({ onerror: function (err, ctx) { ctx.throw('body parse error', 422); } }));
但是如果想要解析multipart/form-data类型,可以用koa-multer
const Koa = require('koa'); const route = require('koa-route'); const multer = require('koa-multer'); const app = new Koa();
app.user(multer());
app.user(function *(){
this.body = this.req.body;
})