GET请求是先后端交互最经常使用的请求之一,经常用来进行查询操做。
那么Koa是如何接收并处理GET请求呢?javascript
// 引入Koa const Koa = require('koa') const app = new Koa() app.use(async ctx => { ctx.body = 'Hello World' }) app.listen(8000) module.exports = app
const http = require('http'); http.createServer(app.callback()).listen(...);
koa2每个请求都会被传入到app.use()方法中,app.use会把请求信息放入到ctx中,咱们能够从ctx中获取请求的基本信息。html
app.use(async ctx => { const url = ctx.url // 请求的url const method = ctx.method // 请求的方法 const query = ctx.query // 请求参数 const querystring = ctx.querystring // url字符串格式的请求参数 ctx.body = { url, method, query, querystring, } })
如今访问localhost:8000?username=zj能够看到浏览器返回java
{ "url": "/?username=zj", "method": "GET", "query": { "username": "zj" }, "querystring": "username=zj" }
请求url是/?username=zj
,请求方法是GET
,请求参数是username=zj
。web
ctx还有一个request对象,是http请求对象,咱们也能够从ctx.request中获取上面的参数。json
app.use(async ctx => { const req = ctx.request const url = req.url // 请求的url const method = req.method // 请求的方法 const query = req.query // 请求参数 const querystring = req.querystring // url字符串格式的请求参数 ctx.body = { url, method, query, querystring, req, } })
浏览器访问结果:后端
{ "url": "/?username=zj", "method": "GET", "query": { "username": "zj" }, "querystring": "username=zj", "req": { "method": "GET", "url": "/?username=zj", "header": { "host": "localhost:8000", "connection": "keep-alive", "cache-control": "max-age=0", "upgrade-insecure-requests": "1", "user-agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36", "accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "accept-encoding": "gzip, deflate, br", "accept-language": "zh-CN,zh;q=0.9", "cookie": "_ga=GA1.1.1379681827.1520244125" } } }
app.use()
方法,接收并处理http GET请求。app.use()
中传入async方法的ctx
对象或者ctx.request
获取到请求信息。