koa2-6

koa-bodyparser中间件

  已经学会如何自己编写代码接收并解析POST请求,这样最基本的功能其实是不用我们自己写的,一定有造好的轮子让我们使用,koa-bodyparser就是一个造好的轮子。我们在koa中把这种轮子就叫做中间件。对于POST请求的处理,koa-bodyparser中间件可以把koa2上下文的formData数据解析到ctx.request.body中。

  

 安装中间件

  使用npm进行安装,需要注意的是我们这里要用–save,因为它在生产环境中需要使用。

npm install --save koa-bodyparser@3

 引入使用

  安装完成后,需要在代码中引入并使用。我们在代码顶部用require进行引入。

onstc  bodyParser = require('koa-bodyparser');

  然后进行使用,如果不使用是没办法调用的,使用代码如下。

app.use(bodyParser());
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('[demo] server is starting at port 3000');
});

猜你喜欢

转载自www.cnblogs.com/xiaofandegeng/p/9108058.html
今日推荐