django-cors-headers: 'Access-Control-Allow-Origin' header missing in DRF

django-cors-headers==2.4.0
Django==2.1 
djangorestframework==3.8.2
Deploying
uWSGI == 2.0.17.1
Nginx == 1.14.0

I have already add corsheaders, corsheaders.middleware.CorsMiddleware to the top, CORS_ORIGIN_ALLOW_ALL=True in my project settings. But when I sent request to webserver, I couldn’t find ‘Access-Control-Allow-Origin’ in response headers. image

About this issue

  • Original URL
  • State: closed
  • Created 6 years ago
  • Reactions: 1
  • Comments: 15 (7 by maintainers)

Most upvoted comments

FWIW I had this same problem but it looked like I wasn’t testing properly. You have to add the Origin header to the request or it won’t work. (Exampie uses httpie)

$ http -h GET https://example.com/api/accounts/profile/ "Authorization: Token abc123...a1b2c3" "Origin: 012.345.678.9"
HTTP/1.1 200 OK
Access-Control-Allow-Origin: *
...

I tried the csrf_exempt trick before discovering the Origin header but it didn’t work for me.

Facing with the same issue despite have already set both of CORS_ORIGIN_ALLOW_ALL, CORS_ALLOW_CREDENTIALS to True.

p.s. Software Stack:

  • Python 3.7.1
  • django 2.1.4
  • django-cors-headers 2.4.0

@olitomas they are orthogonal. CORS_ORIGIN_ALLOW_ALL allows all origins, CORS_URL_REGEX restricts which application URL’s the middleware applies to.

I also noticed that even with:

CORS_ORIGIN_ALLOW_ALL = True

it didn’t work when I had the CORS_URLS_REGEX wrongly configured. So I recommend removing the regex variable when debugging (at least when you haven’t figured out how to get it to work under any circumstances).

I had the same problem and it took me a while to figure out, for anyone interested this is what did it for me.

I needed to add csrf_exempt to each endpoint…like so:

from django.views.decorators.csrf import csrf_exempt

url_patterns = [
    path('test/product_data_feed/<str:brand>/', csrf_exempt(GaProductFeedItemFeedAPIView.as_view()))
]