功能
解析 PUT / POST 请求中的 body,默认支持的格式有(MIME 可定制):
- form
- application/x-www-form-urlencoded
- json
- application/json
- application/json-patch+json
- application/vnd.api+json
- application/csp-report
- text
- text/plain
安装
npm install --save koa-bodyparser
github: koa-bodyparser
使用方法
var Koa = require('koa');
var bodyParser = require('koa-bodyparser');
var app = new Koa();
app.use(bodyParser());
app.use(async ctx => {
// 解析完的数据放在 ctx.request.body 中
// 如果没有解析成功或者无内容,则 body 保持 空,即{}
console.log(ctx.request.method)
console.log(ctx.request.type)
console.log(ctx.request.body)
// 返回 json
ctx.body = ctx.request.body
});
app.listen(3000)
console.log('service listen on port 3000 ...')
测试
form
命令:
curl -d “name=Tom” -d “age=8” http://127.0.0.1:3000
输出:
POST
application/x-www-form-urlencoded
{ name: ‘Tom’, age: ‘8’ }
json
命令:
curl -H “Content-Type: application/json” --data ‘{“name”: “Tom”, “age”: 8}’ http://127.0.0.1:3000
输出:
POST
application/json
{ name: ‘Tom’, age: 8 }