3.koa2请求数据
2018-10-30 本文已影响38人
冷小谦
GET请求数据获取
koa获取GET请求数据是request对象中的query方法或者querystring方法,query返回是格式化好的参数对象,querystring返回的是请求的字符串。
- 1.从上下文中直接获取
请求对象ctx.query
请求字符串ctx.querystring - 2.从上下文的request对象中获取
请求对象ctx.request.query
请求字符串ctx.request.querystring
const Koa = require('koa');
const app = new Koa();
app.use(async(ctx)=>{
let url = ctx.url;
let request = ctx.request;
//从上下文的request对象中获取
let req_query = request.query;
let req_querystring = request.querystring
//从上下文获取
let ctx_query = ctx.query;
let ctx_querystring = ctx.querystring
ctx.body = {
url,
req_query,
req_querystring,
ctx_query,
ctx_querystring
}
})
app.listen(3000,()=>{
console.log('get starting at 3000')
})
POST请求参数
需要解析上下文请求对象req,将POST表单解析成querystring,再讲querystring解析成json
//将POST请求参数字符串解析成JSON
const Koa = require('koa');
const app = new Koa();
app.use(async(ctx)=>{
if(ctx.url === '/' && ctx.method === 'GET'){
let html = `
<h1>koa2 request post demo</h1>
<form action="/" method='POST'>
<p>userName</p>
<input type="userName"/><br />
<p>nickName</p>
<input type="nickName"/><br/>
<p>email</p>
<input type="email"/><br />
<button type='submit'>submit</button>
</form>
`;
ctx.body = html;
}else if(ctx.url === '/' && ctx.method === 'POST'){
console.log(ctx);
let poseData = await parsePostData(ctx);
ctx.body = poseData;
}else{
ctx.body = '<h1>404!!!</h1>'
}
})
app.listen(3000,()=>{
console.log('starting 3000')
})
function parseQueryStr(querystr){
let queryData = {};
let queryStrList = querystr.split('&');
console.log(queryStrList);
for(let [index,querystr] of queryStrList.entries()){
let itemList = querystr.split('=');
console.log(itemList)
queryData[itemList[0]]=decodeURIComponent(itemList[0])
}
return queryData
}
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)
}
})
}