koa2入门学习(3)-路由POST请求

1.用post请求处理URL时,我们会遇到一个问题:post请求通常会发送一个表单、JSON作为request的body发送,但无论是Node.js提供的原始request对象,还是koa提供的request对象,都不提供解析request的body的功能!此时需要借助koa-bodyparser插件。

   npm i koa-bodyparser 

2.app.js代码:

 1 // 模拟一个登陆请求
 2 const Koa = require('koa')
 3 const router = require('koa-router')()
 4 const bodyParser = require('koa-bodyparser')
 5 
 6 const app = new Koa()
 7 
 8 app.use( async (ctx,next) => {
 9    next() 
10 })
11 
12 router.get('/', async(ctx,next) => {
13    ctx.response.body = `<h2> Index </h2>
14      <form action="/login" type="post">
15        <p>name: <input name="name"> </p>
16        <p>password: <input name="password" type="password">        
17         </p>
18        <p> <input type="submit" value="submit"> </p>
19      </form> 
20 `
21 })    
22 
23 router.post('/login', async (ctx,next) => {
24     var name = ctx.request.name || ' ',
25           password = ctx.request.password || ' ';
26     
27     if(name === 'admin' && password === '123456')
28            ctx.response.body = `<h2>Welcome  ${name}</h2>`
29     else
30            ctx.response.body = `<h2>Login failed</h2>
31                    <p> <a href="/">click me try again</a> </p>    
32             `
33 })
34 
35 
36 app.use(bodyParser())
37 app.use(router.routes())
38 app.listen(3000)
39 
40 console.log('app started at port 3000')
41                      

3.效果截图:

 

 

 

   登录失败

 

 

   登陆成功

 

posted @ 2019-10-10 11:31  zoo-x  阅读(1370)  评论(0编辑  收藏  举报