使用
const Koa = require('koa');
const bodyParser = require("koa-bodyparser");
const server = new Koa();
server.listen(8080);
server.use(bodyParser());
server.use(async ctx=>{
if (ctx.url === '/' && ctx.method === 'GET') {
let html = `
<form method="POST" action="/">
<p>account</p>
<input name="account" /><br/>
<p>password</p>
<input name="password" /><br/>
<button type="submit">submit</button>
</form>
`;
ctx.body = html;
} else if (ctx.url === '/' && ctx.method === 'POST') {
let postData = ctx.request.body;
ctx.body = postData;
} else {
ctx.body = '<h1>404</h1>';
}
});
参数
enableTypes:设置解析类型,默认为[‘json’, ‘form’]。
encoding:请求编码。默认值是utf-8。
formLimit:表单大小上限。如果大于此限制,则返回413错误代码。默认是56kb。
jsonLimit:json大小上限。默认是1mb。
textLimit:text大小上限。默认是1mb。
strict:当设置为true时,为严格模式,JSON解析器只接受数组和对象。默认是true。
detectJSON:自定义json请求检测功能。默认是null。
app.use(bodyparser({
detectJSON: function (ctx) {
return /\.json$/i.test(ctx.path);
}
}));
extendTypes:支持扩展类型:
app.use(bodyparser({
extendTypes: {
json: ['application/x-javascript'] // will parse application/x-javascript type body as a JSON string
}
}));
onerror:支持自定义错误句柄,如果koa-bodyparser抛出错误,可以自定义响应,如:
app.use(bodyparser({
onerror: function (err, ctx) {
ctx.throw('body parse error', 422);
}
}));
disableBodyParser:通过ctx.disableBodyParser = true动态禁用body解析器。
app.use(async (ctx, next) => {
if (ctx.path === '/disable') ctx.disableBodyParser = true;
await next();
});
app.use(bodyparser());