HonoRequest
HonoRequest
は c.req
から取得できるオブジェクトで、Request オブジェクトをラップします。
param()
パスパラメータの値を取得します。
// 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()
クエリ文字列パラメータを取得します。
// 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
app.get('/search', async (c) => {
// tags will be string[]
const tags = c.req.queries('tags')
// ...
})
header()
リクエストヘッダーの値を取得します。
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")
を使用してください。
// ❌ 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
タイプの Request ボディをパースします。
app.post('/entry', async (c) => {
const body = await c.req.parseBody()
// ...
})
parseBody()
は次の動作をサポートします。
単一ファイル
const body = await c.req.parseBody()
const data = body['foo']
body['foo']
は (string | File)
です。
複数のファイルがアップロードされた場合、最後のファイルが使用されます。
複数ファイル
const body = await c.req.parseBody()
body['foo[]']
body['foo[]']
は常に (string | File)[]
です。
[]
の接尾辞が必要です。
同じ名前の複数ファイル
const body = await c.req.parseBody({ all: true })
body['foo']
all
オプションはデフォルトで無効になっています。
body['foo']
が複数のファイルの場合、(string | File)[]
にパースされます。body['foo']
が単一ファイルの場合、(string | File)
にパースされます。
ドット記法
dot
オプションを true
に設定すると、戻り値はドット記法に基づいて構造化されます。
次のデータを受信することを想像してください。
const data = new FormData()
data.append('obj.key1', 'value1')
data.append('obj.key2', 'value2')
dot
オプションを true
に設定することで、構造化された値を取得できます。
const body = await c.req.parseBody({ dot: true })
// body is `{ obj: { key1: 'value1', key2: 'value2' } }`
json()
application/json
タイプの Request ボディをパースします。
app.post('/entry', async (c) => {
const body = await c.req.json()
// ...
})
text()
text/plain
タイプの Request ボディをパースします。
app.post('/entry', async (c) => {
const body = await c.req.text()
// ...
})
arrayBuffer()
Request ボディを ArrayBuffer
としてパースします。
app.post('/entry', async (c) => {
const body = await c.req.arrayBuffer()
// ...
})
blob()
Request ボディを Blob
としてパースします。
app.post('/entry', async (c) => {
const body = await c.req.blob()
// ...
})
formData()
Request ボディを FormData
としてパースします。
app.post('/entry', async (c) => {
const body = await c.req.formData()
// ...
})
valid()
検証済みのデータを取得します。
app.post('/posts', async (c) => {
const { title, body } = c.req.valid('form')
// ...
})
利用可能なターゲットは以下のとおりです。
form
json
query
header
cookie
param
使用例については、バリデーションのセクションを参照してください。
routePath()
ハンドラー内で登録されたパスをこのように取得できます。
app.get('/posts/:id', (c) => {
return c.json({ path: c.req.routePath })
})
/posts/123
にアクセスすると、/posts/:id
が返されます。
{ "path": "/posts/:id" }
matchedRoutes()
ハンドラー内でマッチしたルートを返します。これはデバッグに役立ちます。
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
リクエストのパス名。
app.get('/about/me', async (c) => {
const pathname = c.req.path // `/about/me`
// ...
})
url
リクエストの URL 文字列。
app.get('/about/me', async (c) => {
const url = c.req.url // `http://localhost:8787/about/me`
// ...
})
method
リクエストのメソッド名。
app.get('/about/me', async (c) => {
const method = c.req.method // `GET`
// ...
})
raw
生の Request
オブジェクト。
// For Cloudflare Workers
app.post('/', async (c) => {
const metadata = c.req.raw.cf?.hostMetadata?
// ...
})