Skip to content

路由助手

¥Route Helper

路由助手为调试和中间件开发提供了增强的路由信息​​。它允许你访问有关匹配路由和当前正在处理的路由的详细信息。

¥The Route Helper provides enhanced routing information for debugging and middleware development. It allows you to access detailed information about matched routes and the current route being processed.

导入

¥Import

ts
import { Hono } from 'hono'
import {
  matchedRoutes,
  routePath,
  baseRoutePath,
  basePath,
} from 'hono/route'

用法

¥Usage

基本路由信息

¥Basic route information

ts
const app = new Hono()

app.get('/posts/:id', (c) => {
  const currentPath = routePath(c) // '/posts/:id'
  const routes = matchedRoutes(c) // Array of matched routes

  return c.json({
    path: currentPath,
    totalRoutes: routes.length,
  })
})

与子应用协同工作

¥Working with sub-applications

ts
const app = new Hono()
const apiApp = new Hono()

apiApp.get('/posts/:id', (c) => {
  return c.json({
    routePath: routePath(c), // '/posts/:id'
    baseRoutePath: baseRoutePath(c), // '/api'
    basePath: basePath(c), // '/api' (with actual params)
  })
})

app.route('/api', apiApp)

matchedRoutes(c)

返回与当前请求匹配的所有路由(包括中间件)的数组。

¥Returns an array of all routes that matched the current request, including middleware.

ts
app.all('/api/*', (c, next) => {
  console.log('API middleware')
  return next()
})

app.get('/api/users/:id', (c) => {
  const routes = matchedRoutes(c)
  // Returns: [
  //   { method: 'ALL', path: '/api/*', handler: [Function] },
  //   { method: 'GET', path: '/api/users/:id', handler: [Function] }
  // ]
  return c.json({ routes: routes.length })
})

routePath(c)

返回为当前处理程序注册的路由路径模式。

¥Returns the route path pattern registered for the current handler.

ts
app.get('/posts/:id', (c) => {
  console.log(routePath(c)) // '/posts/:id'
  return c.text('Post details')
})

baseRoutePath(c)

返回路由中指定的当前路由的基本路径模式。

¥Returns the base path pattern of the current route as specified in routing.

ts
const subApp = new Hono()
subApp.get('/posts/:id', (c) => {
  return c.text(baseRoutePath(c)) // '/:sub'
})

app.route('/:sub', subApp)

basePath(c)

返回实际请求中嵌入参数的基本路径。

¥Returns the base path with embedded parameters from the actual request.

ts
const subApp = new Hono()
subApp.get('/posts/:id', (c) => {
  return c.text(basePath(c)) // '/api' (for request to '/api/posts/123')
})

app.route('/:sub', subApp)

Hono v4.8 中文网 - 粤ICP备13048890号