okumy/aiohttp-tus

Support Cors headers

Closed this issue · 5 comments

There doesn't seem to be any way currently to add CORS headers

I tried doing this with aiohttp-cors and received an error like this:

<PlainResource 'tus_upload_L3VwbG9hZHM_'  /uploads> already has OPTIONS handler <function upload_options at 0x7fa21b527670>

Hi @Dogfalo,

Yes, there is a known issue with aiohttp-cors, that it doesn’t allow to provide CORS headers for OPTIONS requests cause of the error you mentioned, as it tries to setup a handler for OPTIONS request, but is is already taken

I suggest you to give a try of aiohttp-middlewares and its cors_middleware as it allows to provide CORS headers even for OPTIONS requests

Hope it will work out for you

——

To make it more obvious, I’ll update the documentation with tutorial on how to provide CORS headers for aiohttp-tus library

Thanks for the reply! I am just trying to understand, what makes the aiohttp-middleware different? Does it just add headers into the response of the handler without trying to create a new handler?

The high-level details described in aiohttp-middlewares docs, but if you need more technical details, here they go.

  1. aiohttp-cors registers OPTIONS handler to deal with CORS preflight requests, this resulted in two issues:
    • Inability to use aiohttp-cors with other OPTIONS handlers
    • Inability to use aiohttp-cors with wildcard * handlers, aio-libs/aiohttp-cors#241
  2. While cors_middleware is a regular middleware, which does not register any handlers for dealing with preflight requests. It checks, whether current request is a CORS preflight and if so, does not call handler, but provide an empty response to satisfy CORS needs.

This difference allows cors_middleware to fix both of aiohttp-cors issues as well as simplify dealing with CORS headers for aiohttp.web applications at all, as their setup looks like,

from aiohttp import web
from aiohttp_middlewares import cors_middleware

# Allow CORS requests from URL http://localhost:3000
app = web.Application(
    middlewares=[
        cors_middleware(origins=["http://localhost:3000"])
    ]
)

More examples available in cors_middleware docs.

Hope this makes sense for you.

Makes sense, thanks for the explanation!