梗概
koa-bodyparser是一个用于解析 HTTP 请求体的 koa_中间件。- 它可以将请求体解析为 JSON 格式、表单数据、文本数据等格式,并将解析后的数据挂载到
ctx.request.body上,方便在后续中间件或路由处理程序中使用。
配置选项
enableTypes: 指定要解析的数据类型,默认为['json', 'form', 'text']。encoding: 指定要使用的字符编码,默认为utf-8。formLimit: 指定表单数据大小限制,默认为56kb。jsonLimit: 指定 JSON 数据大小限制,默认为1mb。textLimit: 指定文本数据大小限制,默认为1mb。
示例
const Koa = require('koa');
const bodyParser = require('koa-bodyparser');
const app = new Koa();
app.use(bodyParser());
app.use(async (ctx) => {
// 可以通过 ctx.request.body 获取解析后的请求体数据
console.log(ctx.request.body);
ctx.body = 'Hello, world!';
});
app.listen(3000, () => {
console.log('Server is running on http://localhost:3000');
});更多配置选项请参考官方文档。