koa2---koa-bodyparser中间件
对于POST请求的处理,koa-bodyparser中间件可以把koa2上下文的formData数据解析到ctx.request.body中
安装:
npm install --save koa-bodyparser
使用演示:
1 const Koa = require('koa') 2 const bodyParser = require('koa-bodyparser') 3 4 const app = new Koa() 5 6 app.use(bodyParser()) 7 8 app.use(async ctx => { 9 if (ctx.url === '/' && ctx.method === 'GET') { 10 const html = ` 11 <h1>koa2 request post demo</h1> 12 <form method="POST" action="/"> 13 <p>userName</p> 14 <input name="userName" /><br/> 15 <p>nickName</p> 16 <input name="nickName" /><br/> 17 <p>email</p> 18 <input name="email" /><br/> 19 <button type="submit">submit</button> 20 </form> 21 ` 22 ctx.body = html 23 } else if (ctx.url === '/' && ctx.method === 'POST') { 24 const postData = ctx.request.body 25 ctx.body = postData 26 } else { 27 ctx.body = `<h1>404!!!</h1>` 28 } 29 }) 30 31 app.listen(4000, () => { 32 console.log('[demo] request post is starting at port 4000') 33 })
34
运行:
node demo.js
效果:
koa2学习:https://github.com/chenshenhai/koa2-note