路由
Hono 的路由機制靈活且直觀。讓我們來看一下。
基本
ts
// HTTP Methods
app.get('/', (c) => c.text('GET /'))
app.post('/', (c) => c.text('POST /'))
app.put('/', (c) => c.text('PUT /'))
app.delete('/', (c) => c.text('DELETE /'))
// Wildcard
app.get('/wild/*/card', (c) => {
return c.text('GET /wild/*/card')
})
// Any HTTP methods
app.all('/hello', (c) => c.text('Any Method /hello'))
// Custom HTTP method
app.on('PURGE', '/cache', (c) => c.text('PURGE Method /cache'))
// Multiple Method
app.on(['PUT', 'DELETE'], '/post', (c) =>
c.text('PUT or DELETE /post')
)
// Multiple Paths
app.on('GET', ['/hello', '/ja/hello', '/en/hello'], (c) =>
c.text('Hello')
)
路徑參數
ts
app.get('/user/:name', async (c) => {
const name = c.req.param('name')
// ...
})
或一次取得所有參數
ts
app.get('/posts/:id/comment/:comment_id', async (c) => {
const { id, comment_id } = c.req.param()
// ...
})
可選參數
ts
// Will match `/api/animal` and `/api/animal/:type`
app.get('/api/animal/:type?', (c) => c.text('Animal!'))
正規表達式
ts
app.get('/post/:date{[0-9]+}/:title{[a-z]+}', async (c) => {
const { date, title } = c.req.param()
// ...
})
包含斜線
ts
app.get('/posts/:filename{.+\\.png$}', async (c) => {
//...
})
鏈式路由
ts
app
.get('/endpoint', (c) => {
return c.text('GET /endpoint')
})
.post((c) => {
return c.text('POST /endpoint')
})
.delete((c) => {
return c.text('DELETE /endpoint')
})
分組
您可以使用 Hono 實例對路由進行分組,並使用 route 方法將它們添加到主應用程式。
ts
const book = new Hono()
book.get('/', (c) => c.text('List Books')) // GET /book
book.get('/:id', (c) => {
// GET /book/:id
const id = c.req.param('id')
return c.text('Get Book: ' + id)
})
book.post('/', (c) => c.text('Create Book')) // POST /book
const app = new Hono()
app.route('/book', book)
不更改基礎路徑的分組
您也可以在保持基礎路徑的情況下對多個實例進行分組。
ts
const book = new Hono()
book.get('/book', (c) => c.text('List Books')) // GET /book
book.post('/book', (c) => c.text('Create Book')) // POST /book
const user = new Hono().basePath('/user')
user.get('/', (c) => c.text('List Users')) // GET /user
user.post('/', (c) => c.text('Create User')) // POST /user
const app = new Hono()
app.route('/', book) // Handle /book
app.route('/', user) // Handle /user
基礎路徑
您可以指定基礎路徑。
ts
const api = new Hono().basePath('/api')
api.get('/book', (c) => c.text('List Books')) // GET /api/book
使用主機名稱進行路由
如果包含主機名稱,則運作正常。
ts
const app = new Hono({
getPath: (req) => req.url.replace(/^https?:\/([^?]+).*$/, '$1'),
})
app.get('/www1.example.com/hello', (c) => c.text('hello www1'))
app.get('/www2.example.com/hello', (c) => c.text('hello www2'))
使用 host
標頭值進行路由
如果您在 Hono 建構函式中設定 getPath()
函式,Hono 可以處理 host
標頭值。
ts
const app = new Hono({
getPath: (req) =>
'/' +
req.headers.get('host') +
req.url.replace(/^https?:\/\/[^/]+(\/[^?]*)/, '$1'),
})
app.get('/www1.example.com/hello', (c) => c.text('hello www1'))
// A following request will match the route:
// new Request('http://www1.example.com/hello', {
// headers: { host: 'www1.example.com' },
// })
透過應用此方法,例如,您可以根據 User-Agent
標頭變更路由。
路由優先級
處理程序或中介軟體將按照註冊順序執行。
ts
app.get('/book/a', (c) => c.text('a')) // a
app.get('/book/:slug', (c) => c.text('common')) // common
GET /book/a ---> `a`
GET /book/b ---> `common`
當執行處理程序時,該進程將停止。
ts
app.get('*', (c) => c.text('common')) // common
app.get('/foo', (c) => c.text('foo')) // foo
GET /foo ---> `common` // foo will not be dispatched
如果您有想要執行的中介軟體,請在處理程式上方編寫程式碼。
ts
app.use(logger())
app.get('/foo', (c) => c.text('foo'))
如果您想要有「後備」處理程式,請在其他處理程式下方編寫程式碼。
ts
app.get('/bar', (c) => c.text('bar')) // bar
app.get('*', (c) => c.text('fallback')) // fallback
GET /bar ---> `bar`
GET /foo ---> `fallback`
分組順序
請注意,路由分組的錯誤很難察覺。route()
函數會從第二個參數 (例如 three
或 two
) 中取得儲存的路由,並將其新增到它自己的 (two
或 app
) 路由中。
ts
three.get('/hi', (c) => c.text('hi'))
two.route('/three', three)
app.route('/two', two)
export default app
它將返回 200 回應。
GET /two/three/hi ---> `hi`
但是,如果它們的順序錯誤,則會返回 404。
ts
three.get('/hi', (c) => c.text('hi'))
app.route('/two', two) // `two` does not have routes
two.route('/three', three)
export default app
GET /two/three/hi ---> 404 Not Found