从零一起学koa2(5)---koa-bodyparser中间件

版权声明:转载请注明博客地址谢谢。 https://blog.csdn.net/buppt/article/details/79253132

上一篇中写了如何直接编写代码接收并解析POST请求,比较麻烦,这种比较麻烦的事情一定有中间件让我们使用,koa-bodyparser就是一个。对于POST请求的处理,koa-bodyparser中间件可以把koa2上下文的formData数据解析到ctx.request.body中。

安装

npm install --save koa-bodyparser

例子

引入并使用koa-bodyparser中间件

const bodyParser = require('koa-bodyparser');
app.use(bodyParser()); 

然后就可以直接在ctx.request.body 中获取到JSON格式的POST数据了。
新建app.js文件,稍微修改一下之前的代码即可。

const Koa  = require('koa');
const app = new Koa();

const bodyParser = require('koa-bodyparser');
app.use(bodyParser());
 
app.use(async(ctx)=>{
    if(ctx.url==='/' && ctx.method==='GET'){
        //显示表单页面
        let html=`
            <h1>JSPang Koa2 request POST</h1>
            <form method="POST" action="/">
                <p>userName</p>
                <input name="userName" /><br/>
                <p>age</p>
                <input name="age" /><br/>
                <p>website</p>
                <input name="webSite" /><br/>
                <button type="submit">submit</button>
            </form>
        `;
        ctx.body=html;
    }else if(ctx.url==='/' && ctx.method==='POST'){
         let postData= ctx.request.body;
         ctx.body=postData;
    }else{
        ctx.body='<h1>404!</h1>';
    }
 
});
 
app.listen(3000,()=>{
    console.log('server is starting at port 3000');
});

输入并提交表单,就可以得到JSON格式的数据了。

猜你喜欢

转载自blog.csdn.net/buppt/article/details/79253132