首页 > 其他 > 详细

koa2---koa-bodyparser中间件

时间:2019-11-06 16:17:26      阅读:84      评论:0      收藏:0      [点我收藏+]

对于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

 

 

koa2---koa-bodyparser中间件

原文:https://www.cnblogs.com/caimuguodexiaohongmao/p/11805764.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!