原理
雖然不使用中間件也能獲取請求數據
對於POST請求的處理,koa-bodyparser中間件可以把koa2上下文的formData數據解析到ctx.request.body中。
安裝koa2版本的koa-bodyparser@3中間件
npm install --save koa-bodyparser@3
例子
demo源碼
const Koa = require('koa')
const app = new Koa()
const bodyParser = require('koa-bodyparser')
// 使用ctx.body解析中間件
app.use(bodyParser())
app.use( async ( ctx ) => {
if ( ctx.url === '/' && ctx.method === 'GET' ) {
// 當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' ) {
// 當POST請求的時候,中間件koa-bodyparser解析POST表單里的數據,並顯示出來
let postData = ctx.request.body
ctx.body = postData
} else {
// 其他請求顯示404
ctx.body = '<h1>404!!! o(╯□╰)o</h1>'
}
})
app.listen(3000, () => {
console.log('[demo] request post is starting at port 3000')
})
啟動例子
node post-middleware.js
訪問頁面

提交表單發起POST請求,顯示結果:

參考鏈接:https://chenshenhai.github.io/koa2-note/note/request/post-use-middleware.html
