pythondjangoangulartypescriptcors

Angular CORS with Django


I'm trying to get a simple api with mock data from django. I tried to get the API with Postman and it's fine.

So right now I'm having this situation.

settings.py

"""
Django settings for humatic project.

Generated by 'django-admin startproject' using Django 5.1.

For more information on this file, see
https://docs.djangoproject.com/en/5.1/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/5.1/ref/settings/
"""

from pathlib import Path

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/5.1/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-eojw3i9p*y61oeifwuwheiseuha!8kg+vb#*4i-hd!2-7csrio'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = ['*']
CSRF_TRUSTED_ORIGINS = ["http://localhost:8000"]
CSRF_TRUSTED_ORIGINS = ["http://localhost:4200"]


# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'transactions',
    'rest_framework',
    'corsheaders',
]

CORS_ALLOW_CREDENTIALS = True

CORS_ALLOWED_ORIGINS = [
    "http://localhost:4200",
]

CORS_ALLOW_HEADERS = [
    'content-type',
    'authorization',
]

MIDDLEWARE = [
    "django.middleware.security.SecurityMiddleware",
    "django.contrib.sessions.middleware.SessionMiddleware",
    "corsheaders.middleware.CorsMiddleware",
    "django.contrib.auth.middleware.AuthenticationMiddleware",
    "django.contrib.messages.middleware.MessageMiddleware",
    "django.middleware.clickjacking.XFrameOptionsMiddleware",
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
]


CORS_ORIGIN_WHITELIST = [
    "http://localhost:8000",
    "http://localhost:4200"
]

CORS_ALLOW_METHODS = [
    'GET',
    'POST',
    'PUT',
    'PATCH',
    'DELETE',
    'OPTIONS',
    'HEAD',
]
CORS_ORIGIN_ALLOW_ALL = True
CORS_ALLOW_CREDENTIALS = True
CORS_ALLOW_HEADERS = [
    'content-type',
    'authorization',
    'x-requested-with',
    'accept',
    'origin',
    'x-csrftoken',
]
CORS_EXPOSE_HEADERS = [
    'content-type',
    'authorization',
    'x-requested-with',
    'accept',
    'origin',
    'x-csrftoken',
]
REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSES': [
        'rest_framework.permissions.AllowAny',
    ],
    'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
    'PAGE_SIZE': 10,
}

ROOT_URLCONF = 'humatic.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'humatic.wsgi.application'


# Database
# https://docs.djangoproject.com/en/5.1/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'db.sqlite3',
    }
}


# Password validation
# https://docs.djangoproject.com/en/5.1/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]


# Internationalization
# https://docs.djangoproject.com/en/5.1/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/5.1/howto/static-files/

STATIC_URL = 'static/'

# Default primary key field type
# https://docs.djangoproject.com/en/5.1/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

this is my transactions.component.ts

import { Component, OnInit } from '@angular/core';
import { HttpClient, HttpHeaders, HttpParams } from '@angular/common/http';
import { Observable } from 'rxjs';
import { catchError, map } from 'rxjs/operators';
import { TransactionsService } from '../../services/transactions.service';

@Component({
  selector: 'app-transactions',
  templateUrl: './transactions.component.html',
  styleUrls: ['./transactions.component.scss']
})
export class TransactionsComponent implements OnInit {
  transactions: any[] = [];
  dataLoaded = false;

  constructor(private http: HttpClient, private transactionsService: TransactionsService) {}

  ngOnInit(): void {
    this.loadTransactions();
  }

  loadTransactions(): void {
    console.log('Caricamento delle transazioni iniziato');

    // Configura gli header e le opzioni della richiesta
    const headers = new HttpHeaders({
      'Content-Type': 'application/json'
    });

    // Usa HttpClient per fare la richiesta
    this.http.get<any[]>('http://127.0.0.1:8000/api/dummy-transactions/', { headers, withCredentials: true })
      .pipe(
        map(data => {
          // Elabora i dati se necessario
          console.log('Dati ricevuti:', data);
          return data;
        }),
        catchError(error => {
          // Gestisci gli errori
          console.error('Errore nel caricamento delle transazioni', error);
          throw error; // Rilancia l'errore per ulteriori gestioni
        })
      )
      .subscribe(
        data => {
          this.transactions = data;
          this.dataLoaded = true;
          console.log('Dati caricati e visualizzati');
        },
        error => {
          console.error('Errore nel caricamento delle transazioni', error);
        }
      );
  }
}

HTML

<div *ngIf="dataLoaded">
  <ul>
    <li *ngFor="let transaction of transactions">
      <strong>{{ transaction.type | uppercase }}</strong>: {{ transaction.description }} - {{ transaction.amount }} ({{ transaction.date | date:'short' }})
    </li>
  </ul>
</div>

The result is a page that shows the data, but just if I break loading fast: if not, the api will fail with cors error. Like this: enter image description here

I tryed all.

I also start frontend with: ng serve --proxy-config src/proxy.conf.json. This is the proxy:

{
    "/api": {
      "target": "http://127.0.0.1:8000", 
      "secure": false,
      "changeOrigin": true,
      "logLevel": "debug"
    }
  }

Sorry for the truly bad code and duplicate code, but i changed sooo much that I gave up to clean it again and again. Please help :(


Solution

  • With your code with so many duplicates, I don't think it is easy to find the cause of the error. It might work if you clean it up and use correct settings in settings.py

    from pathlib import Path
    
    # Build paths inside the project like this: BASE_DIR / 'subdir'.
    BASE_DIR = Path(__file__).resolve().parent.parent
    
    # SECURITY WARNING: keep the secret key used in production secret!
    SECRET_KEY = 'django-insecure-eojw3i9p*y61omv$!0tl=c)3gxa!8kg+vb#*4i-hd!2-7csrio'
    
    # SECURITY WARNING: don't run with debug turned on in production!
    DEBUG = True
    
    ALLOWED_HOSTS = []
    
    # Application definition
    INSTALLED_APPS = [
        'django.contrib.admin',
        'django.contrib.auth',
        'django.contrib.contenttypes',
        'django.contrib.sessions',
        'django.contrib.messages',
        'django.contrib.staticfiles',
        'transactions',
        'rest_framework',
        'corsheaders',
    ]
    
    MIDDLEWARE = [
        'django.middleware.security.SecurityMiddleware',
        'django.contrib.sessions.middleware.SessionMiddleware',
        'corsheaders.middleware.CorsMiddleware',  # Add CorsMiddleware before CommonMiddleware
        'django.middleware.common.CommonMiddleware',
        'django.middleware.csrf.CsrfViewMiddleware',
        'django.contrib.auth.middleware.AuthenticationMiddleware',
        'django.contrib.messages.middleware.MessageMiddleware',
        'django.middleware.clickjacking.XFrameOptionsMiddleware',
    ]
    
    # CORS settings
    CORS_ALLOW_CREDENTIALS = True
    
    CORS_ALLOWED_ORIGINS = [
        "http://localhost:4200",  # Angular frontend
        "http://localhost:8100",  # If you're using Ionic or other localhost ports
    ]
    
    CORS_ALLOW_METHODS = [
        'GET',
        'POST',
        'PUT',
        'PATCH',
        'DELETE',
        'OPTIONS',
    ]
    
    CORS_ALLOW_HEADERS = [
        'content-type',
        'authorization',
        'x-requested-with',
    ]
    
    CORS_ALLOW_CREDENTIALS = False  # Set based on your need; usually True if you handle authentication cookies
    
    # Django REST Framework settings
    REST_FRAMEWORK = {
        'DEFAULT_PERMISSION_CLASSES': [
            'rest_framework.permissions.AllowAny',
        ],
        'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
        'PAGE_SIZE': 10,
    }
    
    # Other settings remain unchanged...
    

    And after making changes, don't forget to clean the browser cache using Ctrl + Shift + R.

    Please let me know if it works.