Koa 基礎篇(二)—— 路由與中間件

路由

Koa 中,路由,是一個由一個 URI 和一個特定的 HTTP 方法組成的,涉及到應用如何響應客戶端對某個網站節點的訪問。

簡而言之,就是針對不同的 URI 服務器做出不同的響應。

Koa 中使用路由

Koa 中使用路由可以分爲以下幾步:

  1. 安裝
npm install --save koa-router
  1. 在模塊中引入路由
const router = require("koa-router")()
  1. 啓動路由
app.use(router.routes())
app.use(router.allowedMethods())
  1. 基本使用
router.get("/",async ctx => {
    ctx.body = "hello koa router"
})

完整代碼:

const Koa = require("koa")
const router = require("koa-router")()

let app = new Koa()

router.get("/",async ctx => {
    ctx.body = "hello koa router"
})

app.use(router.routes())
app.use(router.allowedMethods())
app.listen(3000)

運行項目,在瀏覽器訪問本地3000端口,在頁面上就會看到輸出的語句。這就是最簡單的路由。

獲取查詢字符串

其實,不知不覺的,在上面的例子中已經處理了一個 GET 請求。那麼,如何獲取到 GET 請求中的查詢字符串呢?

示例:

router.get("/news",async ctx => {
    console.log(ctx.query)
    ctx.body = "hello koa router"
})

很簡單,通過 ctx.query 就可以獲取到所有的查詢字符串(被封裝爲一個對象)。

動態路由匹配

通過語法 :param 來指定動態路由。

示例:

router.get("/news/:id",async ctx => {
    console.log(ctx.params)
    ctx.body = "hello koa router"
})

通過 ctx.params 就可以獲取到所有動態路由參數(被封裝爲一個對象)。

處理 post 請求

處理 post 請求並不是一件困難的事,直接使用 router.post() 就可以處理了,問題就在於如何獲取 post 請求的請求體。

在原生的 node.js 中,post 請求提交的數據是由一個個數據塊來組成的,所以在接收的時候需要手動進行拼接,這無疑帶來不友好的體驗,所以,使用第三方中間件 koa-bodyparser 來進行請求體的解釋。

  1. 安裝
npm install --save koa-bodyparser
  1. 引入
const parser = require("koa-bodyparser")
app.use(parser())
  1. 使用
router.post("/login",async (ctx,next) => {
    console.log(ctx.request.body)
    ctx.body = "login success"
})

通過 ctx.request.body 就可以獲取到 post 請求體的內容了。

中間件

中間件就是匹配路由之前或匹配路由完成後做的一系列操作。

可以通過中間件來執行代碼,修改請求和響應對象,調用堆棧中的下一個中間件。

應用級中間件

需求:在處理所有請求之前都要打印當前的時間。

顯然,不可能在每個路由中都插入一段代碼來完成這個工作,所以此時就需要用到中間件了。

示例:

app.use(async (ctx,next) => {
    console.log(new Date())
    await next()
})

router.get("/news",async (ctx,next) => {
	console.log("news")
    ctx.body = "this is news page"
})

router.get("/home",async (ctx,next) => {
	console.log("home")
    ctx.body = "this is home page"
})

在上面的例子中,通過一個 use 方法,作爲所有路由的 “攔截器” ,在處理所有路由之前先執行了這個路由裏面的邏輯。

路由中間件

只處理某個具體路由的中間件。

示例:

router.get("/news",async (ctx,next) => {
    console.log("news")
    await next()
})

router.get("/news",async (ctx,next) => {
    ctx.body = "this is news page"
})

訪問該路由時,會在控制檯打印輸出,在頁面上也會有對應的顯示。這說明訪問一個 url 由兩個路由處理了。

錯誤處理中間件

ctx 對象中,有一個 status 屬性用於表示響應狀態碼,從而可以通過響應狀態碼來進行簡單的錯誤處理。

示例:

app.use(async (ctx,next) => {
    if(ctx.status === 404){
        ctx.body = "404 page"
    }
    await next()
})

第三方中間件

第三方中間件就是使用第三方的包進行處理的中間件。比如,使用第三方中間件 koa-static 進行靜態資源的託管。

  1. 安裝
npm install --save koa-static
  1. 引入
const koa_static = require("koa-static")
  1. 配置
app.use(koa_static(path.join(__dirname,"public")))

注意:上面的 public 就是被託管的靜態資源文件夾。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章