From 0e78ec478785b8e760188714044e35981a123616 Mon Sep 17 00:00:00 2001 From: Toby Date: Sat, 28 Sep 2024 02:19:07 +0200 Subject: [PATCH] return cors headers for 404 response as well --- src/index.ts | 43 +++++++++++++++++++++++-------------------- 1 file changed, 23 insertions(+), 20 deletions(-) diff --git a/src/index.ts b/src/index.ts index 1cf1a8d..06ac512 100644 --- a/src/index.ts +++ b/src/index.ts @@ -406,34 +406,37 @@ export class Router { } const route = this.getRoute(req) - - if (!route) - return new Response(this.debugMode ? 'Route not found!' : null, { status: 404 }) - - const handlers = [...this.globalHandlers, ...route.handlers] - const dbg = this.debugMode - let response: Response | undefined - for (const handler of handlers) { - const context = { - ...(ctxExt ?? {}), - env, - req, - dbg, - ctx - } as RouterContext + if (!route) + response = new Response(this.debugMode ? 'Route not found!' : null, { status: 404 }) - const res = await handler(context) + if (!response) { + const handlers = [ + ...this.globalHandlers, + ...(route?.handlers ?? []) + ] - if (res) { - response = res - break + for (const handler of handlers) { + const context = { + ...(ctxExt ?? {}), + env, + req, + dbg: this.debugMode, + ctx + } as RouterContext + + const res = await handler(context) + + if (res) { + response = res + break + } } } if (!response) - return new Response(this.debugMode ? 'Handler did not return a Response!' : null, { status: 404 }) + response = new Response(this.debugMode ? 'Handler did not return a Response!' : null, { status: 404 }) if (this.corsEnabled) { response = new Response(response.body, response)