title: How to solve CORS problem of my Django API?
body: <p>I cannot solve CORS problem in my Django API. When I make a call to this API, I get error:</p>
  
  <blockquote>
    <p>Access to fetch at '<a href="http://localhost:8000/" rel="noreferrer">http://localhost:8000/</a>' from origin
    '<a href="http://localhost" rel="noreferrer">http://localhost</a>' has been blocked by CORS policy: Response to
    preflight request doesn't pass access control check: No
    'Access-Control-Allow-Origin' header is present on the requested
    resource. If an opaque response serves your needs, set the request's
    mode to 'no-cors' to fetch the resource with CORS disabled.</p>
  </blockquote>
  
  <p>To enable CORS, I did <code>pip install django-cors-headers</code> and added the following code to <code>settings.py</code>:</p>
  
  <pre><code>INSTALLED_APPS = [
      'django.contrib.admin',
      'django.contrib.auth',
      'django.contrib.contenttypes',
      'django.contrib.sessions',
      'django.contrib.messages',
      'django.contrib.staticfiles',
      'corsheaders',
  ]
  
  MIDDLEWARE_CLASSES = [
      'corsheaders.middleware.CorsMiddleware',
      'django.middleware.common.CommonMiddleware',
      'django.middleware.security.SecurityMiddleware',
      'django.contrib.sessions.middleware.SessionMiddleware',
      'django.middleware.common.CommonMiddleware',
      'django.middleware.csrf.CsrfViewMiddleware',
      'django.contrib.auth.middleware.AuthenticationMiddleware',
      'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
      'django.contrib.messages.middleware.MessageMiddleware',
      'django.middleware.clickjacking.XFrameOptionsMiddleware',
  ]
  
  CORS_ORIGIN_WHITELIST = [
      'localhost:80',
      'localhost:8000',
      '127.0.0.1:8000'
  ]
  </code></pre>
  
  <p>I should say that I run my project on Docker. This is <code>docker-compose.yml</code>:</p>
  
  <pre><code>version: '2'
  
  services:
    django-docker:
      build:
        context: .
        dockerfile: Dockerfile.django
      container_name: my.django
      image: my-django
      ports:
        - 8000:8000
  
    webapp-docker:
      build:
        context: .
        dockerfile: Dockerfile.webapp
      container_name: my.webapp
      image: my-web
      ports:
        - 80:80
  </code></pre>