前言
接下來這章節將會來講講 ctx 是什麼神奇的東西,而且實際又該如何使用
ctx
首先 ctx 是 context 的縮寫,中文翻譯叫做「上下文」,可以理解成上(request)下(response)的溝通方式,所以原本在 Express 的 req、res,都被包進 ctx 中了。
實際操作
那麼在前面有寫到一段 ctx.body
其實代表的是 ctx.res.body
1 2 3 4 5 6 7 8 9 10
| const koa = require('koa'); const app = new koa();
app.use(async (ctx) => { ctx.body = 'Hello Koa'; });
app.listen(3000, async ()=>{ console.log('Example app listening on port 3000!'); });
|
那麼假設今天我們要取得使用者請求的 url 呢?
1 2 3 4 5 6 7 8 9 10 11
| const koa = require('koa'); const app = new koa();
app.use(async (ctx) => { console.log(ctx.url); ctx.body = 'Hello Koa'; });
app.listen(3000, async ()=>{ console.log('Example app listening on port 3000!'); });
|
此時我們輸入 localhost:3000/users
,那麼就會取得使用者請求的頁面
![ctx.url]()
基本上以上就是原生 koa 路由的製作方式。
那麼由於它的 API 太多,所以這邊直接附上 request 與 response 的 API
(實際開發會使到的大概可能只有 3 成,所以等等提供的 API 可能很多,但不用過度擔心,因為並不會全部都要記。)
request
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
| ctx.header ctx.headers ctx.method ctx.method= ctx.url ctx.url= ctx.originalUrl ctx.origin ctx.href ctx.path ctx.path= ctx.query ctx.query= ctx.querystring ctx.querystring= ctx.host ctx.hostname ctx.fresh ctx.stale ctx.socket ctx.protocol ctx.secure ctx.ip ctx.ips ctx.subdomains ctx.is() ctx.accepts() ctx.acceptsEncodings() ctx.acceptsCharsets() ctx.acceptsLanguages() ctx.get()
|
response
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| ctx.body ctx.body= ctx.status ctx.status= ctx.message ctx.message= ctx.length= ctx.length ctx.type= ctx.type ctx.headerSent ctx.redirect() ctx.attachment() ctx.set() ctx.append() ctx.remove() ctx.lastModified= ctx.etag=
|
參考連結
koa Context