Open ferbs opened 3 years ago
Have you tried router#allowedMethods?
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());
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
}));
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:
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?