Is your feature request related to a problem? Please describe.
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
A web browser sends a pre-flight OPTIONS request to verify that a request can be sent. The framework itself should provide direct support (without the need for a helper library).
Describe the solution you'd like
I would like the ability to at least configure (at the app level) allowed origins, allowed methods and allowed headers for OPTIONS verbs that will return 200 to an appropriate client, without executing the underlying endpoint.
Optionally, it would be nice to be able to configure at an endpoint level the cors options.
Additional context
sanic-cors is utterly flawed. It executes the endpoint when the OPTIONS method is used against the api, causing web clients to execute the same method twice, which as you can imagine, is quite problematic.
@mikepc it looks like the sanic-cors plugin will let you do this if you specify automatic_options when wrapping sanic.
CORS(app, automatic_options=True)
@mikepc
I'm the author of Sanic-CORS. I responded to your issue you raised on the Sanic-CORS repo about this, but I will make another response on here because there are a lot more users in this repo.
When using Sanic-CORS, the issue of executing the same method twice is usually meant to be handled by the user's route handler, by checking if the request is a pre-flight OPTIONS request like this:
@app.route('/my_function', methods=['GET','OPTIONS'])
async def my_function(request):
if request.method == 'OPTIONS':
return HTTPResonse(None, 200)
# continue my_function...
Or if you don't want to do that for every route function, you can turn on automatic_options to let Sanic-CORS do that for you:
app = Sanic(__main__)
cors = CORS(app, automatic_options=True)
_OR the config method_:
app = Sanic(__main__)
app.config['CORS_AUTOMATIC_OPTIONS'] = True
cors = CORS(app)
A side note, as Sanic-CORS is a Sanic-Plugins-Framework application, the recommended method to attach the plugin to the app is instead of doing it like that (the old Flask-like way), do it the SPF way:
from spf import SanicPluginsFramework
from sanic_cors.extension import cors
app = Sanic(__main__)
spf = SanicPluginsFramework(app)
spf.register_plugin(cors, automatic_options=True)
# And all other plugins:
# spf.register_plugin(plugin2...)
In response to the feature-request:
My feeling is this is not a feature that belongs in Sanic.
As always, its a trade-off between super-fast light-weight framework, vs bundled features and extended capabilities.
Other frameworks such as Flask leave CORS functionality up to plugins to handle, and I think Sanic should remain in the same boat.
I agree with @ashleysommer. This is something that Sanic-CORS provides, and is not something we would want to add into the core code base. Please feel free to continue the conversation, but I am closing the issue.