Koa2 和 Express 中間件對比

koa2 中間件

koa2的中間件是經過 async await 實現的,中間件執行順序是「洋蔥圈」模型。express

中間件之間經過next函數聯繫,當一箇中間件調用 next() 後,會將控制權交給下一個中間件, 直到下一個中間件再也不執行 next() 後, 將會沿路折返,將控制權依次交換給前一箇中間件。json

如圖:api


image


koa2 中間件實例

app.js:promise

const Koa = require('koa');
const app = new Koa();


// logger
app.use(async (ctx, next) => {
    console.log('第一層 - 開始')
    await next();
    const rt = ctx.response.get('X-Response-Time');
    console.log(`${ctx.method} ----------- ${ctx.url} ----------- ${rt}`);
    console.log('第一層 - 結束')
});


// x-response-time
app.use(async (ctx, next) => {
    console.log('第二層 - 開始')
    const start = Date.now();
    await next();
    const ms = Date.now() - start;
    ctx.set('X-Response-Time', `${ms}ms`);
    console.log('第二層 - 結束')
});


// response
app.use(async ctx => {
    console.log('第三層 - 開始')
    ctx.body = 'Hello World';
    console.log('第三層 - 結束')
});


app.listen(3000);

執行app.js後,瀏覽器訪問 http://localhost:3000/text , 控制檯輸出結果:瀏覽器

第一層 - 開始
第二層 - 開始
第三層 - 開始
第三層 - 結束
第二層 - 結束
打印第一次執行的結果: GET -------- /text ------ 4ms
第一層 - 結束

koa2 中間件應用

下面是一個登錄驗證的中間件:session

loginCheck.js:app

module.exports = async (ctx, next) => {
    if (ctx.session.username) {
        // 登錄成功,需執行 await next(),以繼續執行下一步
        await next()
        return
    }
    // 登錄失敗,禁止繼續執行,因此不須要執行 next()
    ctx.body = {
        code: -1,
        msg: '登錄失敗'
    }
}

在刪除操做中使用 loginCheck.js :koa

router.post('/delete', loginCheck, async (ctx, next) => {
    const author = ctx.session.username
    const id = ctx.query.id
    // handleDelete() 是一個處理刪除的方法,返回一個 promise
    const result = await handleDelete(id, author)

    if (result) {
        ctx.body = {
            code: 0,
            msg: '刪除成功'
        }
    } else {
        ctx.body = {
            code: -1,
            msg: '刪除失敗'
        }
    }
})

express 中間件

與 koa2 中間件不一樣的是,express中間件一個接一個的順序執行, 一般會將 response 響應寫在最後一箇中間件中異步

主要特色:

  • app.use 用來註冊中間件
  • 遇到 http 請求,根據 path 和 method 判斷觸發哪些中間件
  • 實現 next 機制,即上一個中間件會經過 next 觸發下一個中間件

express 中間件實例

const express = require('express')

const app = express()

app.use((req, res, next) => {
    console.log('第一層 - 開始')
    setTimeout(() => {
        next()
    }, 0)
    console.log('第一層 - 結束')
})

app.use((req, res, next) => {
    console.log('第二層 - 開始')
    setTimeout(() => {
        next()
    }, 0)
    console.log('第二層 - 結束')
})

app.use('/api', (req, res, next) => {
    console.log('第三層 - 開始')
    res.json({
        code: 0
    })
    console.log('第三層 - 結束')
})

app.listen(3000, () => {
    console.log('server is running on port 3000')
})

執行app.js後,瀏覽器訪問 http://localhost:3000/api , 控制檯輸出結果:async

第一層 - 開始
第一層 - 結束
第二層 - 開始
第二層 - 結束
第三層 - 開始
第三層 - 結束

由於上面各個中間件中的 next() 是異步執行的,因此 打印結果是線行輸出的。

若是取消上面next()的異步執行,直接按以下方式:

const express = require('express')

const app = express()

app.use((req, res, next) => {
    console.log('第一層 - 開始')
    next()
    console.log('第一層 - 結束')
})

app.use((req, res, next) => {
    console.log('第二層 - 開始')
    next()
    console.log('第二層 - 結束')
})

app.use('/api', (req, res, next) => {
    console.log('第三層 - 開始')
    res.json({
        code: 0
    })
    console.log('第三層 - 結束')
})

app.listen(3000, () => {
    console.log('server is running on port 3000')
})

執行app.js後,瀏覽器訪問 http://localhost:3000/api , 控制檯輸出結果:

第一層 - 開始
第二層 - 開始
第三層 - 開始
第三層 - 結束
第二層 - 結束
第一層 - 結束

可見,express 的中間件也能夠造成「洋蔥圈」模型,可是通常在express中不會這麼作,由於 express 的 response 通常在最後一箇中間件,因此其它中間件 next() 後的代碼影響不到最終結果。

express 中間件應用

下面是一個登錄驗證的中間件:

loginCheck.js:

module.exports = (req, res, next) => {
    if (req.session.username) {
        // 登錄成功,需執行 next(),以繼續執行下一步
        next()
        return
    }
    // 登錄失敗,禁止繼續執行,因此不須要執行 next()
    ctx.body = {
        code: -1,
        msg: '登錄失敗'
    }
}

在刪除操做中使用 loginCheck.js :

router.post('/delete', loginCheck, (req, res, next) => {
    const author = req.session.username
    const id = req.query.id
    // handleDelete() 是一個處理刪除的方法,返回一個 promise
    const result = handleDelete(id, author)

    return result.then(val => {
        if (val) {
            ctx.body = {
                code: 0,
                msg: '刪除成功'
            }
        } else {
            ctx.body = {
                code: -1,
                msg: '刪除失敗'
            }
        }
    })
})
相關文章
相關標籤/搜索