Skip to content

Commit

Permalink
return cors headers for 404 response as well
Browse files Browse the repository at this point in the history
  • Loading branch information
tsndr committed Sep 28, 2024
1 parent fd7dce7 commit 0e78ec4
Showing 1 changed file with 25 additions and 22 deletions.
47 changes: 25 additions & 22 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -406,34 +406,37 @@ export class Router<Env = any, CtxExt = {}, ReqExt = {}> {
}

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<Env, CtxExt, ReqExt>

const res = await handler(context)

if (res) {
response = res
break
if (!route)
response = new Response(this.debugMode ? 'Route not found!' : null, { status: 404 })

if (!response) {
const handlers = [
...this.globalHandlers,
...(route?.handlers ?? [])
]

for (const handler of handlers) {
const context = {
...(ctxExt ?? {}),
env,
req,
dbg: this.debugMode,
ctx
} as RouterContext<Env, CtxExt, ReqExt>

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)
Expand Down

0 comments on commit 0e78ec4

Please sign in to comment.