Middleware(Hono)
「Handler」
回傳Response的單元
「Middleware」
在Handler的之前與之後執行,處理Request與Response
Request->MA->MB->MC->Handler->MC->MB->MA->Response,如同洋蔥一般
Handler
回傳Response物件,每次只會呼叫一個Handler
Middleware
await next(),不回傳值並呼叫下一個Middleware
或是回傳Response後提早離開
可使用app.use或app.HTTP_METOHD替Handler註冊Middleware
code:js
// 套用所有路徑
app.use(logger())
// 套用特定路徑
app.use('/posts/*', cors())
// 套用特定路徑和方法
app.post('/posts/*', basicAuth())
app.post('/posts', (c) => c.next('Created!', 201))
以註冊的順序執行
在next前的內容則會先執行,後的會最後執行
code:js
app.use(async (_, next) => {
console.log('middleware 1 start')
await next()
console.log('middleware 1 end')
})
app.use(async (_, next) => {
console.log('middleware 2 start')
await next()
console.log('middleware 2 end')
})
app.use(async (_, next) => {
console.log('middleware 3 start')
await next()
console.log('middleware 3 end')
})
app.get('/', (c) => {
console.log('handler')
return c.text('Hello!')
})