Appearance
HonoRequest
HonoRequest
是一个可以从 c.req
中获取的对象,它封装了一个 请求 对象。
¥The HonoRequest
is an object that can be taken from c.req
which wraps a Request object.
param()
获取路径参数的值。
¥Get the values of path parameters.
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()
获取查询字符串参数。
¥Get querystring parameters.
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
¥Get multiple querystring parameter values, e.g. /search?tags=A&tags=B
ts
app.get('/search', async (c) => {
// tags will be string[]
const tags = c.req.queries('tags')
// ...
})
header()
获取请求标头值。
¥Get the request header value.
ts
app.get('/', (c) => {
const userAgent = c.req.header('User-Agent')
return c.text(`Your user agent is ${userAgent}`)
})
警告
当不带参数调用 c.req.header()
时,返回记录中的所有键均为小写。
¥When c.req.header()
is called with no arguments, all keys in the returned record are lowercase.
如果你想要获取带有大写名称的标头的值,请使用 c.req.header(“X-Foo”)
。
¥If you want to get the value of a header with an uppercase name, use 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
的请求主体
¥Parse Request body of type multipart/form-data
or application/x-www-form-urlencoded
ts
app.post('/entry', async (c) => {
const body = await c.req.parseBody()
// ...
})
parseBody()
支持以下行为。
¥parseBody()
supports the following behaviors.
单个文件
¥Single file
ts
const body = await c.req.parseBody()
const data = body['foo']
body['foo']
是 (string | File)
。
¥body['foo']
is (string | File)
.
如果上传了多个文件,将使用最后一个文件。
¥If multiple files are uploaded, the last one will be used.
多个文件
¥Multiple files
ts
const body = await c.req.parseBody()
body['foo[]']
body['foo[]']
始终是 (string | File)[]
。
¥body['foo[]']
is always (string | File)[]
.
需要 []
后缀。
¥[]
postfix is required.
多个同名文件
¥Multiple files with same name
ts
const body = await c.req.parseBody({ all: true })
body['foo']
all
选项默认禁用。
¥all
option is disabled by default.
如果
body['foo']
是多个文件,它将被解析为(string | File)[]
。¥If
body['foo']
is multiple files, it will be parsed to(string | File)[]
.如果
body['foo']
是单个文件,它将被解析为(string | File)
。¥If
body['foo']
is single file, it will be parsed to(string | File)
.
点符号
¥Dot notation
如果你设置 dot
选项 true
,则返回值基于点符号构造。
¥If you set the dot
option true
, the return value is structured based on the dot notation.
想象一下接收以下数据:
¥Imagine receiving the following data:
ts
const data = new FormData()
data.append('obj.key1', 'value1')
data.append('obj.key2', 'value2')
你可以通过设置 dot
选项 true
来获取结构化值:
¥You can get the structured value by setting the dot
option true
:
ts
const body = await c.req.parseBody({ dot: true })
// body is `{ obj: { key1: 'value1', key2: 'value2' } }`
json()
解析 application/json
类型的请求主体
¥Parses the request body of type application/json
ts
app.post('/entry', async (c) => {
const body = await c.req.json()
// ...
})
text()
解析 text/plain
类型的请求主体
¥Parses the request body of type text/plain
ts
app.post('/entry', async (c) => {
const body = await c.req.text()
// ...
})
arrayBuffer()
将请求主体解析为 ArrayBuffer
¥Parses the request body as an ArrayBuffer
ts
app.post('/entry', async (c) => {
const body = await c.req.arrayBuffer()
// ...
})
blob()
将请求主体解析为 Blob
。
¥Parses the request body as a Blob
.
ts
app.post('/entry', async (c) => {
const body = await c.req.blob()
// ...
})
formData()
将请求主体解析为 FormData
。
¥Parses the request body as a FormData
.
ts
app.post('/entry', async (c) => {
const body = await c.req.formData()
// ...
})
valid()
获取经过验证的数据。
¥Get the validated data.
ts
app.post('/posts', async (c) => {
const { title, body } = c.req.valid('form')
// ...
})
可用目标如下。
¥Available targets are below.
form
json
query
header
cookie
param
有关使用示例,请参阅 验证部分。
¥See the Validation section for usage examples.
routePath()
你可以像这样在处理程序中检索已注册的路径:
¥You can retrieve the registered path within the handler like this:
ts
app.get('/posts/:id', (c) => {
return c.json({ path: c.req.routePath })
})
如果你访问 /posts/123
,它将返回 /posts/:id
:
¥If you access /posts/123
, it will return /posts/:id
:
json
{ "path": "/posts/:id" }
matchedRoutes()
它在处理程序中返回匹配的路由,这对于调试很有用。
¥It returns matched routes within the handler, which is useful for debugging.
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
请求路径名。
¥The request pathname.
ts
app.get('/about/me', async (c) => {
const pathname = c.req.path // `/about/me`
// ...
})
url
请求 URL 字符串。
¥The request url strings.
ts
app.get('/about/me', async (c) => {
const url = c.req.url // `http://localhost:8787/about/me`
// ...
})
method
请求的方法名称。
¥The method name of the request.
ts
app.get('/about/me', async (c) => {
const method = c.req.method // `GET`
// ...
})
raw
原始 Request
对象。
¥The raw Request
object.
ts
// For Cloudflare Workers
app.post('/', async (c) => {
const metadata = c.req.raw.cf?.hostMetadata?
// ...
})