Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django CORS on static asset

Tags:

cors

django

I'm using Django as a backend, and have run into cross origin issues which I had fixed using the corsheaders package in settings. So far, all my GET endpoints work, thanks to:

CORS_ORIGIN_ALLOW_ALL = True

However, I'm now trying to access a static file on the django backend, located as such:

http://localhost:8000/static/image.jpg

The browser client however gets the familiar error as before:

Access to XMLHttpRequest at ... from origin ... has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Any ideas? Thanks

like image 727
user339946 Avatar asked Apr 18 '19 17:04

user339946


1 Answers

I'm assuming you're using the built-in staticfiles app to serve your static files in development. When using the runserver managment command along with staticfiles, it uses a WSGI handler to serve static files that bypasses middleware. (Django docs)

The solution is to disable the WSGI handler and instead set up normal Django URL routing to the staticfiles views that do get processed by middleware. You can disable the WSGI handler by running python manage.py runserver --nostatic. When you use --nostatic it will handle static URLs the same as all other URLs, through your Django urlconf, so you'll need to include the staticfiles URLs in your root urlconf like so: (see Static file development view)

if settings.DEBUG:
    from django.contrib.staticfiles.urls import staticfiles_urlpatterns
    urlpatterns += staticfiles_urlpatterns()
like image 111
sparkyb Avatar answered Oct 23 '22 16:10

sparkyb