功能
解析 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 }