Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Endpoints for CORS requests #130

Open
ferbs opened this issue Sep 3, 2021 · 3 comments
Open

Endpoints for CORS requests #130

ferbs opened this issue Sep 3, 2021 · 3 comments

Comments

@ferbs
Copy link

ferbs commented Sep 3, 2021

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
Copy link

erwinv commented Nov 19, 2021

Have you tried router#allowedMethods?

@ferbs
Copy link
Author

ferbs commented Nov 19, 2021

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
Copy link

jdrydn commented Dec 21, 2021

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants