koa get post request

table of Contents

 

principle:

note:

Example:


principle:

For processing POST request, koa2 no method for acquiring parameters of the package, need to request the object req by parsing the context as the native Node.js, a POST form data parsed into query string (for example: a = 1 & b = 2 & c = 3), then parse the query string into JSON format (e.g.: { "a": "1", "b": "2", "c": "3"})

note:

       ctx.request request object is encapsulated in context, ctx.req native node.js is the HTTP request object to provide context, a context Similarly ctx.response response object after encapsulation, ctx.res context is provided native node.js HTTP request object.

Example:

   

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

app.use( async ( ctx ) => {
    if ( ctx.url === '/' && ctx.method === 'GET' ) {
        // 当GET请求时候返回表单页面
        let html = `
      <h1>koa2 request post demo</h1>
      <form method="POST" action="/">
        <p>userName</p>
        <input name="userName" /><br/>
        <p>nickName</p>
        <input name="nickName" /><br/>
        <p>email</p>
        <input name="email" /><br/>
        <button type="submit">submit</button>
      </form>
    `
        ctx.body = html
    } else if ( ctx.url === '/' && ctx.method === 'POST' ) {
        // 当POST请求的时候,解析POST表单里的数据,并显示出来
        let postData = await parsePostData( ctx )
        ctx.body = postData
    } else {
        // 其他请求显示404
        ctx.body = '<h1>404!!! o(╯□╰)o</h1>'
    }
})
/**
 * 解析上下文里node原生请求的post参数
 * */

function parsePostData(ctx){
    return new Promise((resolve,reject)=>{
        try {
            console.log(ctx.req === ctx.request)
            let postData = '';
            ctx.req.addListener('data',(data)=>{
                postData += data;
            })
            ctx.req.addListener('end',()=>{
                let parseData = parseQueryStr(postData);
                resolve(parseData)
            })
        }catch (err) {
            reject(err)
        }
    })
}

/**
 * 将POST请求的参数字符串解析成json
 */

function parseQueryStr(queryStr) {
    console.log('queryStr',queryStr)
      let queryData = {};
      let queryStrList = queryStr.split('&');
      console.log(queryStrList);
      for(let [index,queryStr] of queryStrList.entries()){
          console.log(index,queryStr)
          let itemList = queryStr.split('=');
          queryData[itemList[0]] = decodeURIComponent(itemList[1]);
      }
      return queryData
}

app.listen(3000, () => {
    console.log('[demo] request post is starting at port 3000')
})

 

Published 31 original articles · won praise 13 · views 10000 +

Guess you like

Origin blog.csdn.net/qq_38694034/article/details/105252080
Recommended