Skip to content

Accepts 助手

Accepts 助手用于处理请求中的 Accept 系列请求头。

导入

ts
import { Hono } from 'hono'
import { accepts } from 'hono/accepts'

accepts()

accepts() 函数会读取 Accept 请求头(例如 Accept-Encoding 与 Accept-Language),并返回最合适的取值。

ts
import { accepts } from 'hono/accepts'

app.get('/', (c) => {
  const accept = accepts(c, {
    header: 'Accept-Language',
    supports: ['en', 'ja', 'zh'],
    default: 'en',
  })
  return c.json({ lang: accept })
})

AcceptHeader 类型

AcceptHeader 类型的定义如下:

ts
export type AcceptHeader =
  | 'Accept'
  | 'Accept-Charset'
  | 'Accept-Encoding'
  | 'Accept-Language'
  | 'Accept-Patch'
  | 'Accept-Post'
  | 'Accept-Ranges'

配置项

required header: AcceptHeader

目标 Accept 请求头。

required supports: string[]

应用所支持的请求头取值。

required default: string

默认返回的值。

optional match: (accepts: Accept[], config: acceptsConfig) => string

自定义匹配函数。

Released under the MIT License.