router icon indicating copy to clipboard operation
router copied to clipboard

Endpoints for CORS requests

Open ferbs opened this issue 3 years ago • 3 comments

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?

ferbs avatar Sep 03 '21 00:09 ferbs

Have you tried router#allowedMethods?

erwinv avatar Nov 19 '21 10:11 erwinv

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());

ferbs avatar Nov 19 '21 19:11 ferbs

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
}));

jdrydn avatar Dec 21 '21 11:12 jdrydn