Appearance
请求 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
}>()
设置请求 ID
¥Set Request ID
你在标头中设置了一个自定义请求 ID(默认值:X-Request-Id
),中间件将使用该值,而不是生成新的 ID:
¥You set a custom request ID in the header (default: X-Request-Id
), the middleware will use that value instead of generating a new one:
ts
const app = new Hono()
app.use('*', requestId())
app.get('/', (c) => {
return c.text(`${c.get('requestId')}`)
})
const res = await app.request('/', {
headers: {
'X-Request-Id': 'your-custom-id',
},
})
console.log(await res.text()) // your-custom-id
如果你想禁用此功能,请将 headerName
选项 设置为空字符串。
¥If you want to disable this feature, set headerName
option to an empty string.
选项
¥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()
.