方法覆寫中間件
此中間件會根據表單、標頭或查詢的值,執行指定方法的處理器(與請求的實際方法不同),並返回其回應。
導入
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 方法,您可以將值 DELETE
放入名為 _method
的屬性中並發送。然後將會執行 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' }))
選項
必要 app: Hono
您的應用程式中使用的 Hono
實例。
可選 form: string
表單鍵,其值包含方法名稱。預設值為 _method
。
可選 header: boolean
標頭名稱,其值包含方法名稱。
可選 query: boolean
查詢參數鍵,其值包含方法名稱。