koa2 --- koa-bodyparser middleware

For the POST request is processed, koa-bodyparser middleware can koa2 formData context of data analysis to ctx.request.body

installation:

npm install --save koa-bodyparser

Demo:

 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

run:

node demo.js

effect:

 

 

 

 koa2 learning: https://github.com/chenshenhai/koa2-note

 

 

Guess you like

Origin www.cnblogs.com/caimuguodexiaohongmao/p/11805764.html