From 9b302150f2ac0587e57c4043d7bdf368229296b2 Mon Sep 17 00:00:00 2001 From: "Daniel W. Steinbrook" Date: Thu, 7 Dec 2023 23:04:41 -0500 Subject: [PATCH] Add CORS headers to allow API calls from other websites --- app/server.py | 19 +++++++++++++++++-- requirements.txt | 1 + 2 files changed, 18 insertions(+), 2 deletions(-) diff --git a/app/server.py b/app/server.py index e3d3f7d..fd39107 100644 --- a/app/server.py +++ b/app/server.py @@ -3,6 +3,7 @@ from urllib.parse import urlparse from aiohttp import web +from aiohttp_cors import ResourceOptions, setup as cors_setup import sentry_sdk from sentry_sdk.integrations.aiohttp import AioHttpIntegration @@ -78,12 +79,26 @@ def run_server( sentry_sdk.set_tag( "backend_url", backend_url ) # Tag all requests for the lifecycle of the app with the overpass URL used + app = web.Application() - app["backend_client"] =backend_client( - backend_url, user_agent, cache_dir, cache_days, cache_size) + app["backend_client"] = backend_client( + backend_url, user_agent, cache_dir, cache_days, cache_size + ) app.add_routes( [ web.get(r"/tiles/{zoom:\d+}/{x:\d+}/{y:\d+}.json", tile_handler), ] ) + + # Allow web apps running on any domain to make API calls to this server + cors = cors_setup(app, defaults={ + "*": ResourceOptions( + allow_credentials=True, + expose_headers="*", + allow_headers="*", + ) + }) + for route in list(app.router.routes()): + cors.add(route) + web.run_app(app, port=port) diff --git a/requirements.txt b/requirements.txt index 4e3653f..57fc753 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,4 +1,5 @@ aiohttp==3.8.4 +aiohttp_cors==0.7.0 aiopg==1.4.0 osm2geojson==0.2.3 shapely==2.0.1