好久没使nodejs的koa框架,都忘记怎么获取参数了,特此记录下来
在koa中GET请求参数获取
1.通过request接收
接受的方法有两种:
query:返回的是格式化好的参数对象
querystring:返回的是请求字符串
async function test(ctx) { ctx.status = 200; let url = ctx.url; let request = ctx.request; let req_query = request.query; let req_queryString = request.querystring; let name = req_query.name; let text = req_query.text; ctx.body = { url: url, req_query: req_query, req_queryString: req_queryString, name: name, text: text } }
2.直接从ctx中获取Get请求
async function test(ctx) { ctx.status = 200; let url = ctx.url; let ctx_query = ctx.query; let ctx_querystring = ctx.querystring; let name = ctx_query.name; let text = ctx_query.text; ctx.body = { url: url, query: ctx_query, queryString: ctx_querystring, name: name, text: text } }
返回结果
{
"url": "/api/test?name=aaa&text=111",
"query": {
"name": "aaa",
"text": "111"
},
"queryString": "name=aaa&text=111",
"name": "aaa",
"text": "111"
}