HonoRequest

HonoRequest 是从 c.req 获取的对象,它封装了一个 Request 对象。

param()

获取路径参数。

  1. // 获取单个路径参数
  2. app.get('/entry/:id', async (c) => {
  3. const id = c.req.param('id')
  4. // ...
  5. })
  6. // 一次获取全部路径参数
  7. app.get('/entry/:id/comment/:commentId', async (c) => {
  8. const { id, commentId } = c.req.param()
  9. })

query()

获取查询字符串参数。

  1. // 获取单个 query 参数
  2. app.get('/search', async (c) => {
  3. const query = c.req.query('q')
  4. })
  5. // 一次获取所有 query 参数
  6. app.get('/search', async (c) => {
  7. const { q, limit, offset } = c.req.query()
  8. })

queries()

获取同一 query 参数的多个值,例如 /search?tags=A&tags=B

  1. app.get('/search', async (c) => {
  2. // tags 是 string[]
  3. const tags = c.req.queries('tags')
  4. // ...
  5. })

header()

获取请求头的值。

  1. app.get('/', (c) => {
  2. const userAgent = c.req.header('User-Agent')
  3. return c.text(`Your user agent is ${userAgent}`)
  4. })

注意:c.req.header() 不传参数时,返回的所有键名都是 小写。 如果需要获取带大写的 Header 名称,应显式传入 Header 名称。

  1. // ❌ 不可用
  2. const headerRecord = c.req.header()
  3. const foo = headerRecord['X-Foo']
  4. // ✅ 可用
  5. const foo = c.req.header('X-Foo')

parseBody()

解析请求体中的 multipart/form-dataapplication/x-www-form-urlencoded 数据。

  1. app.post('/entry', async (c) => {
  2. const body = await c.req.parseBody()
  3. // ...
  4. })

支持的行为

单文件

  1. const body = await c.req.parseBody()
  2. const data = body['foo']

body['foo'] 类型是 (string | File)。 如果上传了多个文件,将只取最后一个。

多文件

  1. const body = await c.req.parseBody()
  2. body['foo[]']

body['foo[]'] 总是 (string | File)[]必须使用 [] 后缀

同名多文件或多字段

如果 <input type="file" multiple /> 或多个同名复选框 <input type="checkbox" name="favorites" value="Hono"/>, 可以使用 all: true 选项:

  1. const body = await c.req.parseBody({ all: true })
  2. body['foo']
  • body['foo'] 是多个文件时,会解析为 (string | File)[]
  • 当是单文件时,解析为 (string | File)

Dot notation(点语法)

如果设置 dot: true,返回值会基于点语法生成结构化对象。

例如:

  1. const data = new FormData()
  2. data.append('obj.key1', 'value1')
  3. data.append('obj.key2', 'value2')
  1. const body = await c.req.parseBody({ dot: true })
  2. // body = { obj: { key1: 'value1', key2: 'value2' } }

json()

解析 application/json 类型的请求体。

  1. app.post('/entry', async (c) => {
  2. const body = await c.req.json()
  3. // ...
  4. })

text()

解析 text/plain 类型的请求体。

  1. app.post('/entry', async (c) => {
  2. const body = await c.req.text()
  3. // ...
  4. })

arrayBuffer()

将请求体解析为 ArrayBuffer

  1. app.post('/entry', async (c) => {
  2. const body = await c.req.arrayBuffer()
  3. // ...
  4. })

blob()

将请求体解析为 Blob

  1. app.post('/entry', async (c) => {
  2. const body = await c.req.blob()
  3. // ...
  4. })

formData()

将请求体解析为 FormData

  1. app.post('/entry', async (c) => {
  2. const body = await c.req.formData()
  3. // ...
  4. })

valid()

获取验证后的数据。

  1. app.post('/posts', async (c) => {
  2. const { title, body } = c.req.valid('form')
  3. // ...
  4. })

可用的验证目标有:

  • form
  • json
  • query
  • header
  • cookie
  • param

具体用法见 Validation 章节

routePath

警告: 在 v4.8.0 中已弃用,请改用 Route Helper 中的 routePath()

  1. app.get('/posts/:id', (c) => {
  2. return c.json({ path: c.req.routePath })
  3. })

当访问 /posts/123 时返回:

  1. { "path": "/posts/:id" }

matchedRoutes

警告: 在 v4.8.0 中已弃用,请改用 Route Helper 中的 matchedRoutes()

它会返回当前请求匹配到的所有路由,常用于调试。

  1. app.use(async function logger(c, next) {
  2. await next()
  3. c.req.matchedRoutes.forEach(({ handler, method, path }, i) => {
  4. const name =
  5. handler.name ||
  6. (handler.length < 2 ? '[handler]' : '[middleware]')
  7. console.log(
  8. method,
  9. ' ',
  10. path,
  11. ' '.repeat(Math.max(10 - path.length, 0)),
  12. name,
  13. i === c.req.routeIndex ? '<- respond from here' : ''
  14. )
  15. })
  16. })

path

获取请求的 pathname。

  1. app.get('/about/me', async (c) => {
  2. const pathname = c.req.path // `/about/me`
  3. // ...
  4. })

url

获取完整请求 URL 字符串。

  1. app.get('/about/me', async (c) => {
  2. const url = c.req.url // `http://localhost:8787/about/me`
  3. // ...
  4. })

method

获取请求方法名。

  1. app.get('/about/me', async (c) => {
  2. const method = c.req.method // `GET`
  3. // ...
  4. })

raw

获取原始的 Request 对象。

  1. // 在 Cloudflare Workers 中使用
  2. app.post('/', async (c) => {
  3. const metadata = c.req.raw.cf?.hostMetadata?
  4. // ...
  5. })