Method Not Allowed 中间件
请求路径匹配已注册路由,但请求方法不受支持时,Method Not Allowed 中间件返回带有 Allow 响应头的 405 Method Not Allowed 响应。不使用此中间件时,Hono 会在这种情况下返回 404 Not Found。
导入
ts
import { Hono } from 'hono'
import { methodNotAllowed } from 'hono/method-not-allowed'用法
ts
const app = new Hono()
app.use(methodNotAllowed({ app }))
app.get('/hello', (c) => c.text('Hello!'))
app.post('/hello', (c) => c.text('Posted!'))
// PUT /hello -> 405 Method Not Allowed
// Allow: GET, HEAD, POST可以通过 onMethodNotAllowed 选项自定义响应:
ts
app.use(
methodNotAllowed({
app,
onMethodNotAllowed: (c, methods) =>
c.json({ error: 'Method Not Allowed' }, 405, {
Allow: methods.join(', '),
}),
})
)选项
required app: Hono
应用使用的 Hono 实例。中间件从该实例已注册的路由中收集每个路径允许的方法。
optional onMethodNotAllowed: (c: Context, allowedMethods: string[]) => Response | Promise<Response>
生成包含 Allow 响应头的响应。默认情况下,中间件返回 405 Method Not Allowed,并将 Allow 设置为允许的方法。