跳转到正文

HonoRequest ​

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

param() ​

获取路径参数的值。

ts
// Captured params
app
.
get
('/entry/:id', async (
c
) => {
const
id
=
c
.
req
.
param
('id')
// ... }) // Get all params at once
app
.
get
('/entry/:id/comment/:commentId', async (
c
) => {
const {
id
,
commentId
} =
c
.
req
.
param
()
})

query() ​

获取查询字符串参数。

ts
// Query params
app
.
get
('/search', async (
c
) => {
const
query
=
c
.
req
.
query
('q')
}) // Get all params at once
app
.
get
('/search', async (
c
) => {
const {
q
,
limit
,
offset
} =
c
.
req
.
query
()
})

queries() ​

获取查询字符串参数的多个值,例如 /search?tags=A&tags=B。

ts
app
.
get
('/search', async (
c
) => {
// tags will be string[] const
tags
=
c
.
req
.
queries
('tags')
// ... })

获取请求头的值。

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

注意

不传参数调用 c.req.header() 时,返回记录中的所有键都为小写。

如果要获取名称包含大写字母的请求头的值, 请使用 c.req.header(“X-Foo”)。

ts
// ❌ Will not work
const headerRecord = c.req.header()
const foo = headerRecord['X-Foo']

// ✅ Will work
const foo = c.req.header('X-Foo')

parseBody() ​

解析 multipart/form-data 或 application/x-www-form-urlencoded 类型的请求体。

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

parseBody() 支持以下行为。

单个文件

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

body['foo'] 的类型为 (string | File)。

如果上传多个文件,将使用最后一个文件。

多个文件 ​

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

body['foo[]'] 的类型始终为 (string | File)[]。

必须使用 [] 后缀。

多个同名文件或字段 ​

当输入字段允许多个文件(<input type="file" multiple />),或有多个同名的复选框(<input type="checkbox" name="favorites" value="Hono"/>)时,可以这样处理。

ts
const 
body
= await
c
.
req
.
parseBody
({
all
: true })
body
['foo']

all 选项默认关闭。

  • 如果 body['foo'] 包含多个文件,将解析为 (string | File)[]。
  • 如果 body['foo'] 只有一个文件,将解析为 (string | File)。

点号表示法 ​

将 dot 选项设为 true 后,返回值会根据点号表示法组织为结构化对象。

假设收到以下数据:

ts
const 
data
= new
FormData
()
data
.
append
('obj.key1', 'value1')
data
.
append
('obj.key2', 'value2')

将 dot 选项设为 true,即可获得结构化的值:

ts
const 
body
= await
c
.
req
.
parseBody
({
dot
: true })
// body is `{ obj: { key1: 'value1', key2: 'value2' } }`

json() ​

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

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

text() ​

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

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

arrayBuffer() ​

将请求体解析为 ArrayBuffer。

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

blob() ​

将请求体解析为 Blob。

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

formData() ​

将请求体解析为 FormData。

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

valid() ​

获取经过验证的数据。

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

可用的目标如下。

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

使用示例请参阅验证章节。

routePath ​

注意

在 v4.8.0 中弃用:此属性已弃用。请改用路由辅助工具中的 routePath()。

可以在处理程序中这样获取注册的路径:

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

访问 /posts/123 时,将返回 /posts/:id:

json
{ "path": "/posts/:id" }

matchedRoutes ​

注意

在 v4.8.0 中弃用:此属性已弃用。请改用路由辅助工具中的 matchedRoutes()。

在处理程序中返回匹配到的路由,适合用于调试。

ts
app
.
use
(async function
logger
(
c
,
next
) {
await
next
()
c
.
req
.
matchedRoutes
.
forEach
(({
handler
,
method
,
path
},
i
) => {
const
name
=
handler
.
name
||
(
handler
.
length
< 2 ? '[handler]' : '[middleware]')
console
.
log
(
method
,
' ',
path
,
' '.
repeat
(
Math
.
max
(10 -
path
.
length
, 0)),
name
,
i
===
c
.
req
.
routeIndex
? '<- respond from here' : ''
) }) })

path ​

请求的路径名。

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

url ​

请求的 URL 字符串。

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

method ​

请求的方法名称。

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

raw ​

原始的 Request 对象。

ts
// For Cloudflare Workers
app.post('/', async (c) => {
  const metadata = c.req.raw.cf?.hostMetadata?
  // ...
})

cloneRawRequest() ​

从 HonoRequest 克隆原始 Request 对象。即使请求体已被验证器或 HonoRequest 方法读取,也可以使用。

ts
import { 
Hono
} from 'hono'
const
app
= new
Hono
()
import {
cloneRawRequest
} from 'hono/request'
import {
validator
} from 'hono/validator'
app
.
post
(
'/forward',
validator
('json', (
data
) =>
data
),
async (
c
) => {
// Clone after validation const
clonedReq
= await
cloneRawRequest
(
c
.
req
)
// Does not throw the error await
clonedReq
.
json
()
// ... } )

基于 MIT 许可证发布。