跳至內容

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-dataapplication/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)[]

需要 [] 後綴。

具有相同名稱的多個檔案

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()

您可以在處理常式中檢索已註冊的路徑,如下所示

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

如果您存取 /posts/123,它將會回傳 /posts/:id

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

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
// `https://127.0.0.1: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?
  // ...
})

依據 MIT 授權發布。