代码之家  ›  专栏  ›  技术社区  ›  Phabreetion

使用Django的Angular CORS

  •  0
  • Phabreetion  · 技术社区  · 1 年前

    我试图从django获取一个带有模拟数据的简单api。 我试着用Postman获取API,这很好。

    所以现在我有这种情况。

    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'
    

    这是我的交易。组件。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>
    

    结果是一个显示数据的页面,但如果我快速加载中断: 否则,api将失败,并出现cors错误。这样地: enter image description here

    我都试过了。

    我还从前端开始使用:ng-serve--proxy-config-src/proxy.conf.json。 这是代理:

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

    很抱歉出现了真正糟糕的代码和重复的代码,但我改变了太多,以至于我放弃了一次又一次地清理它。 请帮忙:(

    1 回复  |  直到 1 年前
        1
  •  1
  •   Feenix Net    1 年前

    由于你的代码有这么多重复项,我认为很难找到错误的原因。 如果你清理它并在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...
    

    更改后,不要忘记使用Ctrl+Shift+R清理浏览器缓存。

    请告诉我它是否有效。