Method Override 中间件
此中间件根据表单、请求头或查询参数的值,执行与请求实际方法不同的指定方法的处理器,并返回其响应。
导入
ts
import { Hono } from 'hono'
import { methodOverride } from 'hono/method-override'用法
ts
const app = new Hono()
// If no options are specified, the value of `_method` in the form,
// e.g. DELETE, is used as the method.
app.use('/posts', methodOverride({ app }))
app.delete('/posts', (c) => {
// ....
})示例
HTML 表单无法发送 DELETE 方法,因此可以在名为 _method 的属性中放入 DELETE 并发送,之后就会执行 app.delete() 的处理器。
HTML 表单:
html
<form action="/posts" method="POST">
<input type="hidden" name="_method" value="DELETE" />
<input type="text" name="id" />
</form>应用:
ts
import { methodOverride } from 'hono/method-override'
const app = new Hono()
app.use('/posts', methodOverride({ app }))
app.delete('/posts', () => {
// ...
})可以修改默认值,或改用请求头值和查询参数值:
ts
app.use('/posts', methodOverride({ app, form: '_custom_name' }))
app.use(
'/posts',
methodOverride({ app, header: 'X-METHOD-OVERRIDE' })
)
app.use('/posts', methodOverride({ app, query: '_method' }))选项
required app: Hono
应用中使用的 Hono 实例。
optional form: string
值包含方法名称的表单字段键。 默认值为 _method。
optional header: boolean
值包含方法名称的请求头名称。
optional query: boolean
值包含方法名称的查询参数键。