在koa中,獲取GET請求數(shù)據(jù)源頭是koa中request對象中的query方法或querystring方法,query返回是格式化好的參數(shù)對象,querystring返回的是請求字符串,由于ctx對request的API有直接引用的方式,所以獲取GET請求數(shù)據(jù)有兩個途徑。
1.是從上下文中直接獲取
請求對象ctx.query,返回如 { a:1, b:2 }
請求字符串 ctx.querystring,返回如 a=1&b=2
2.是從上下文的request對象中獲取
請求對象ctx.request.query,返回如 { a:1, b:2 }
請求字符串 ctx.request.querystring,返回如 a=1&b=2
貼代碼:
const Koa = require('koa')
const config = require('../config')
const app = new Koa()
app.use( async ( ctx ) => {
let url = ctx.url
// 從上下文的request對象中獲取
let request = ctx.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( config.port ,()=>{console.log(`端口號為${config.port}的node項目啟動成功`);})

貼代碼

模擬get請求