You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular对接Django API偶发CORS错误求助

解决Django + Angular 偶发CORS错误问题

我用Django提供带模拟数据的API,Postman请求完全正常,但Angular页面只有在快速中断加载时能显示数据,正常加载时会触发CORS错误。

已尝试的配置:
启动Angular时使用ng serve --proxy-config src/proxy.conf.json,代理配置如下:

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

Django 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'

Angular 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);
        }
      );
  }
}

Angular 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>

问题根源及修复步骤

1. 清理Django settings.py中的重复/冲突配置

你的settings.py里存在重复定义的CORS配置(比如CORS_ALLOW_CREDENTIALS、CORS_ALLOW_HEADERS被多次赋值),同时CORS_ORIGIN_ALLOW_ALL = True和CORS_ALLOWED_ORIGINS共存会导致逻辑冲突,另外中间件顺序错误也会影响CORS头的正常返回。

修改后的settings.py关键部分:

# 修复CSRF_TRUSTED_ORIGINS,合并两个地址不要覆盖
CSRF_TRUSTED_ORIGINS = ["http://localhost:8000", "http://localhost:4200"]

# 清理重复的CORS配置,保留一套完整的
CORS_ALLOW_CREDENTIALS = True
# 开发环境可使用CORS_ORIGIN_ALLOW_ALL,生产环境建议指定具体域名
# CORS_ORIGIN_ALLOW_ALL = True
CORS_ALLOWED_ORIGINS = [
    "http://localhost:4200",
    "http://127.0.0.1:4200"
]
CORS_ALLOW_METHODS = [
    'GET',
    'POST',
    'PUT',
    'PATCH',
    'DELETE',
    'OPTIONS',
    'HEAD',
]
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',
]

# 修复中间件顺序,CorsMiddleware必须在CommonMiddleware之前
MIDDLEWARE = [
    "django.middleware.security.SecurityMiddleware",
    "django.contrib.sessions.middleware.SessionMiddleware",
    "corsheaders.middleware.CorsMiddleware",
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    "django.contrib.auth.middleware.AuthenticationMiddleware",
    "django.contrib.messages.middleware.MessageMiddleware",
    "django.middleware.clickjacking.XFrameOptionsMiddleware",
]

2. 调整Angular请求地址,让代理生效

当前请求直接写绝对路径http://127.0.0.1:8000/api/dummy-transactions/会绕过Angular代理,直接跨域请求Django。修改为相对路径:

this.http.get<any[]>('/api/dummy-transactions/', { headers, withCredentials: true })

3. 重启服务

修改配置后,重启Django和Angular服务,确保新配置生效。


内容的提问来源于stack exchange,提问作者Phabreetion

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.19 07:35:53