koajs / cors

Cross-Origin Resource Sharing(CORS) for koa
Other
732 stars 80 forks source link

Fix/non preflight options #63

Open sripberger opened 5 years ago

sripberger commented 5 years ago

Not all OPTIONS requests are CORS preflight requests from browsers. This middleware correctly checks to make sure that Access-Control-Request-Method is present before fully treating a request as a preflight-- however, it does so after skipping over any of the usual logic for "actual" requests.

The result is that access control headers will not be set for any OPTIONS requests, even though they will still continue into downstream middlewares like other "actual" requests:

https://github.com/koajs/cors/blob/71c4d00b170f52fd1324e9fd028816408867f8a6/index.js#L101-L107

This blocks any and all cross-origin OPTIONS requests that are not preflights, breaking features in other popular Koa middlewares-- such as the automatic 'allowed methods' middlewares from koa-router-- when accessed cross-origin.

I've fixed the problem by moving this check into the if statement that separates "actual" requests from preflight ones.

I've also removed some unnecessary await keywords, rationale explained here:

https://eslint.org/docs/rules/no-return-await

I can of course live without this second bit if you guys have some reason I'm not aware of for wanting to return await in these scenarios. Any performance change will be far below noticeable. I just figured I might as well, and can roll it back if I have to. :+1:

Thanks!