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
メソッド名を値として持つクエリパラメーターのキー。