zheewang
3/27/2018 - 2:45 AM

Koa Post data processing

const ethSC = require('./SmartContract.js');

// callSC.callSmartContract(1);

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

const route = require('koa-route');

//对于POST请求的处理,koa2没有封装获取参数的方法
var invoke = async (ctx,next) => {

      // 当POST请求的时候,解析POST表单里的数据,并显示出来
      let postData = await parsePostData( ctx );
      let opt = parseInt(postData['option']);
      
      console.log("this is option data %d",opt);
      ethSC.callSmartContract(opt);
};

// 解析上下文里node原生请求的POST参数
function parsePostData( ctx ) {
    return new Promise((resolve, reject) => {
      try {
        let postdata = "";
        ctx.req.addListener('data', (data) => {
          postdata += data;
        })
        ctx.req.addListener("end",function(){
          let parseData = parseQueryStr( postdata );
          resolve( parseData );
        })
      } catch ( err ) {
        reject(err);
      }
    })
  }
  
  // 将POST请求参数字符串解析成JSON
  function parseQueryStr( queryStr ) {
    let queryData = {};
    let queryStrList = queryStr.split('&');
    console.log( "parseQueryStr--original post data is  "+ queryStrList );
    for (  let [ index, queryStr ] of queryStrList.entries()  ) {
      let itemList = queryStr.split('=');
      queryData[ itemList[0] ] = decodeURIComponent(itemList[1])
    }
    return queryData
  }
  

var index = function(ctx) { 
    ctx.response.type="txt";
    ctx.response.body= "hello world";
}

// app.use(route.post("/",opt(3)));
//app.use(route.get('/3'),invoke(3));
app.use(route.get('/', index));
app.use(route.post('/',invoke));
app.listen(3100);