For CORS [^ cors] support when implementing an API server with aiohttp Server, a module called aiohttp_cors is provided by the aiohttp official.
[^ cors]: Cross-origin Resource Sharing (CORS)-HTTP | MDN
However, when I read Usage, it seems that it is not straightforward because it is necessary to wrap each resource and each route with cors.add. It is convenient to be able to make detailed settings, but there are also cases where "I just want to allow all requests".
So, this time, I will write about how to support CORS roughly without using aiohttp_cors.
from aiohttp import web
@web.middleware
async def cors_middleware(request, handler):
response = await handler(request)
response.headers['Access-Control-Allow-Origin'] = '*'
return response
app = web.Application(middlewares=[cors_middleware])
**It's the end. ** **
Just add the ʻAccess-Control-Allow-Origin: *` header to every response.
If you say "What about*," you should be able to specify the Origin that is allowed in the environment variable.
import os
from aiohttp import web
@web.middleware
async def cors_middleware(request, handler):
response = await handler(request)
response.headers['Access-Control-Allow-Origin'] = os.environ.get('CORS_ALLOW_ORIGIN', '*')
return response
app = web.Application(middlewares=[cors_middleware])
By the way, it does not correspond to the case where Preflight Request flies. If you want to respond, you can make a guy who will respond to all ʻOPTION` requests.
It's a really crude story, so I'd like you to think about whether security is okay or not.
Recommended Posts