Koa2學習(三)GET請求
GET請求是前后端交互最常用的請求之一,常常用來進行查詢操作。
那么Koa是如何接收並處理GET請求呢?
創建一個服務
// 引入Koa
const Koa = require('koa')
const app = new Koa()
app.use(async ctx => {
ctx.body = 'Hello World'
})
app.listen(8000)
module.exports = app
- 其中ctx是Koa2非常重要的一個上下文對象,可以把它理解為一個全局的頂層對象,Koa2里面絕大部分的屬性和方法都可以通過ctx對象獲取。
- 其中ctx.body就是返回的html內容。
- app.listen(...)是koa2的一個語法糖,等於運行了下面這兩個方法,實質就是調用http模塊創建一個監聽端口的服務。
- 每收到一個http請求,koa就會調用通過app.use()注冊的async函數,並傳入ctx和next參數。
const http = require('http');
http.createServer(app.callback()).listen(...);
接收請求
koa2每一個請求都會被傳入到app.use()方法中,app.use會把請求信息放入到ctx中,我們可以從ctx中獲取請求的基本信息。
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可以看到瀏覽器返回
{
"url": "/?username=zj",
"method": "GET",
"query": {
"username": "zj"
},
"querystring": "username=zj"
}
請求url是/?username=zj
,請求方法是GET
,請求參數是username=zj
。
ctx還有一個request對象,是http請求對象,我們也可以從ctx.request中獲取上面的參數。
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
獲取到請求信息。