koa框架学习记录(4)

koa-bodyparser中间件

koa-bodyparser就是一个造好的轮子。我们在koa中把这种轮子就叫做中间件。对于POST请求的处理,koa-body中间件技术parser中间件可以把koa2上下文的formData数据解析到ctx.request前端开发工程师.body中。

安装中间件

npm install --save koa-bodyparser@3
安装完中间件技术成后,需要在代码中引入并使用。我们在代码中间件技术顶部用require进行引入。
const bodyParser = require('koa-bodyparser');
然后进行使用
app.use(bodyP前端开发工资一般多少arser());
在代码中使用后,直接可以用ctx.request.body进行获中间件取POST请求参数,中间件 自动给我们作了解析。

const Koa= require('koa');
const app = new Koa();
const bodyParser = require('koa-bodyparser');

app.use(bodyParser());

app.use(async(ctx)=>{
if(ctx.url==='/' && ctx.method==='GET'){
//显示表单页面
let html=`
<h1>JSPang Koa2 request POST</h1>
<form method="POST" action="/">
<p>userName</p>
<input name="userName" /><br/>
<p>age</p>
<input name="age" /><br/>
<p>website</p>
<input name="webSite" /><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>';
}

});


app.listen(3000,()=>{
console.log('[demo] server is starting at port 3000');
});