對于POST請求的處理,koa-bodyparser中間件可以把koa2上下文的formData數(shù)據(jù)解析到ctx.request.body中
npm install --save koa-bodyparser@3
const Koa = require('koa')
const app = new Koa()
const bodyParser = require('koa-bodyparser')
const config = require('../config')
//使用ctx.body解析中間件
app.use(bodyParser())
app.use(async(ctx)=>{
if(ctx.url==='/' && ctx.method==='GET'){
//當(dāng)GET請求時候返回表單頁面
let html = `
<h1>koa2 request post demo</h1>
<form method="POST" action="/">
<p>userName</p>
<input name="userName" /><br/>
<p>nickName</p>
<input name="nickName" /><br/>
<p>email</p>
<input name="email" /><br/>
<button type="submit">submit</button>
</form>
`
ctx.body = html
}else if(ctx.url==='/' && ctx.method=='POST'){
//當(dāng)post請求的時候,中間件koa-bodyparser解析post表單哩的數(shù)據(jù),并顯示出來
let postData = ctx.request.body
ctx.body = postData
}else{
//其他請求顯示404
ctx.body = '<h1>404.</h1>';
}
})
app.listen( config.port ,()=>{console.log(`端口號為${config.port}的node項目啟動成功`);})

koa-post koa-bodyparser