koajs / router

Router middleware for Koa. Maintained by @forwardemail and @ladjs.
MIT License
849 stars 174 forks source link

Endpoints for CORS requests #130

Open ferbs opened 3 years ago

ferbs commented 3 years ago

For nested routes, @koa/router rejects CORS preflight requests as 404s because there's not an explicit endpoint defined for these OPTIONS requests. As a workaround, I'm explicitly adding endpoints, eg:

router.options(somePathDefinition, (ctx: Koa.Context, next: Koa.Next) => next()); 

Where somePathDefinition is a path-to-regex. Is there something better to use than the above matching '(.*)' but easier to maintain than a whitelist of routes?

erwinv commented 2 years ago

Have you tried router#allowedMethods?

ferbs commented 2 years ago

Thanks. Just tried it but it breaks some tests, returning an undesired 200 to endpoints that don't want requests from browsers. I tried applying it to just an individual nested router without success, getting 404s again with router.use(router.allowedMethods()); instead of app.use(router.allowedMethods());

jdrydn commented 2 years ago

I think perhaps you're after @koa/cors?

If you run the cors(...) middleware in router.use, then it'll execute, if and only if, a route is matched, and return earlier than your route logic:

const cors = require('@koa/cors');

router.use(cors({
  // CORS options here
}));

router.post('/auth', exampleAuthFunction);

You could also place the CORS middleware at the higher app level & have it return before it even reaches the router middleware.

const cors = require('@koa/cors');

app.use(cors({
  // CORS options here
}));