adamchainz / django-cors-headers

Django app for handling the server headers required for Cross-Origin Resource Sharing (CORS)

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

DRF-Cors not working for static files on django default serving static files routes.

lijunhaoabroad opened this issue · comments

urlpatterns = [
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

Hi, I have a drf api server, the cors package all works fine with api, but when my app on the other domain tries to get the static files from django, the cors package didn't include the allow origin header, it failed.

I only saw a solution that I have to manually serve static files with a view like I did with api (or I can edit the request to carry the head response in the @def section ), then the cors will send the allow access header with it.

Is there any logic behind this?

The whitenoise package can be used to serve static files out of Django: http://whitenoise.evans.io/en/stable/ . You don't need to build your own view. With modern Python and the good caching headers it sets up, there's really no performance concern. Try that, otherwise yes you'll have to duplicate your CORS haeders in nginx, or whatever serves static files.

Hi,
Is there any ways to just use this django-cors-headers package to serve static files ?
I don't want to use another package and pythonanywhere won't let me edit server config file, otherwise I would just edit it on the server instead.
thanks!

No, this package only adds headers.

If I may ask , why this package didn't add headers for static files routes? Try to learn new things here....

If you're using runserver from the static package, it serves the files directly without them passing through middleware

See https://docs.djangoproject.com/en/3.0/ref/contrib/staticfiles/#runserver

I don't have time to answer all questions like this though, please see the Django "Getting Help" FAQ: https://docs.djangoproject.com/en/3.0/faq/help/