koa(一) koa-bodyparser

koa中解析body的中间件,支持json,form,text,可以用来获取post提交的数据

原生Node.js获取post提交的数据

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
function parsePostData(ctx) {
return new Promise((resolve, reject) => {
try {
let postdata = "";
ctx.req.on('data', data => {
postdata += data;
});
ctx.req.on('end', () => {
resolve(postdata);
});
} catch (error) {
reject(error);
}
});
}

安装

1
npm install --save koa-bodyparser

使用

1
2
3
4
5
6
7
8
9
10
11
12
const Koa = require('koa');
const bodyParse = require('koa-bodyparser');

const app = new Koa();

app.use(bodyParse());

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;
});

链接

文档