cookiecutter-django
cookiecutter-django copied to clipboard
API calls from Swagger UI page fail while running the project at "localhost:8000" due to CORS
What happened?
- New project generated with
use_drf: y - When making an API request from the swagger UI at
http://localhost:8000/api/docs/, the API call fails due to CORS policy
What should've happened instead?
The API call should have worked with no issues
Additional details
The issue is due to project running on localhost:8000 while the SERVERS option in drf-spectacular settings has the url http://127.0.0.1:8000.
It seems like there is more than one option to fix this:
- one way is to set the
CORS_ALLOWED_ORIGINS = ["http://localhost:8000", "http://127.0.0.1:8000"]in local settings so that api calls fromlocalhost:8000work fine (django-cors-headers docs) - the other option is to remove
SERVERSfrom drf-spectacular
I'm leaning towards the second option and that's because I don't think it's a good idea to be able to make API call to a production server when working locally. Also, When the project is deployed to production, it doesn't make a lot of sense to see the option for making API calls to "127.0.01:8000" in the swagger UI page.
So, before creating a PR, I wanted to check if there are good reasons to keep SERVERS in drf-spectacular settings (or maybe there is a better third option)
Hum, that's a good point. What is the implication of the second option, if we remove SERVERS? Is it just using the current host?
This config was suggested in the code review, and at the time it seemed like a good idea. However, given this extra problem with CORS policy, it now seems not so great. We could set it to the right values in local.py and production.py, but maybe the 2nd option you suggest is much simpler...
(Just my ideas at a glance, I haven't looked into it in details yet)
Tools like https://stoplight.io can use the SERVERS to generate code samples of requests pointing to the "correct" domain.
What is the implication of the second option, if we remove SERVERS? Is it just using the current host?
yes, it will use the current host.
Sample request when running on 127.0.0.1:8000:
Sample request when running on localhost:8000:
