cookiecutter-django icon indicating copy to clipboard operation
cookiecutter-django copied to clipboard

API calls from Swagger UI page fail while running the project at "localhost:8000" due to CORS

Open ghazi-git opened this issue 3 years ago • 3 comments
trafficstars

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 cors

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 from localhost:8000 work fine (django-cors-headers docs)
  • the other option is to remove SERVERS from 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)

ghazi-git avatar Feb 15 '22 20:02 ghazi-git

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)

browniebroke avatar Feb 15 '22 22:02 browniebroke

Tools like https://stoplight.io can use the SERVERS to generate code samples of requests pointing to the "correct" domain.

luzfcb avatar Feb 15 '22 22:02 luzfcb

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: docs_page_without_servers_127_0_0_1 Sample request when running on localhost:8000: docs_page_without_servers_localhost

ghazi-git avatar Feb 16 '22 07:02 ghazi-git