Skip to content

请求 ID 中间件

¥Request ID Middleware

请求 ID 中间件为每个请求生成一个唯一的 ID,你可以在处理程序中使用该 ID。

¥Request ID Middleware generates a unique ID for each request, which you can use in your handlers.

导入

¥Import

ts
import { Hono } from 'hono'
import { requestId } from 'hono/request-id'

用法

¥Usage

你可以通过应用请求 ID 中间件的处理程序和中间件中的 requestId 变量访问请求 ID。

¥You can access the Request ID through the requestId variable in the handlers and middleware to which the Request ID Middleware is applied.

ts
const app = new Hono()

app.use('*', requestId())

app.get('/', (c) => {
  return c.text(`Your request id is ${c.get('requestId')}`)
})

如果你想要明确指定类型,请导入 RequestIdVariables 并将其传入 new Hono() 的泛型中。

¥If you want to explicitly specify the type, import RequestIdVariables and pass it in the generics of new Hono().

ts
import type { RequestIdVariables } from 'hono/request-id'

const app = new Hono<{
  Variables: RequestIdVariables
}>()

选项

¥Options

optional limitLength:number

请求 ID 的最大长度。默认为 255

¥The maximum length of the request ID. The default is 255.

optional 标头名称:string

¥optional headerName: string

用于请求 ID 的标头名称。默认为 X-Request-Id

¥The header name used for the request ID. The default is X-Request-Id.

optional 生成器:(c: Context) => string

¥optional generator: (c: Context) => string

请求 ID 生成函数。默认情况下,它使用 crypto.randomUUID()

¥The request ID generation function. By default, it uses crypto.randomUUID().

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