Middleware Method Not Allowed
Le middleware Method Not Allowed renvoie une réponse 405 Method Not Allowed avec un en-tête Allow lorsque le chemin de la requête correspond à une route enregistrée, mais que la méthode de la requête n’est pas prise en charge. Sans ce middleware, Hono renvoie une réponse 404 Not Found dans ce cas.
Importation
ts
import { Hono } from 'hono'
import { methodNotAllowed } from 'hono/method-not-allowed'Utilisation
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, POSTVous pouvez personnaliser la réponse avec l’option onMethodNotAllowed :
ts
app.use(
methodNotAllowed({
app,
onMethodNotAllowed: (c, methods) =>
c.json({ error: 'Method Not Allowed' }, 405, {
Allow: methods.join(', '),
}),
})
)Options
obligatoire app: Hono
L’instance de Hono utilisée par l’application. Le middleware collecte les méthodes autorisées pour chaque chemin à partir des routes enregistrées.
facultatif onMethodNotAllowed: (c: Context, allowedMethods: string[]) => Response | Promise<Response>
Génère la réponse, y compris son en-tête Allow. Par défaut, le middleware renvoie une réponse 405 Method Not Allowed dont l’en-tête Allow contient les méthodes autorisées.