我正在尝试从 django 获取带有模拟数据的简单 api。 我尝试使用 Postman 获取 API,没问题。
所以我现在就遇到这样的情况。
设置.py
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*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',
]
CORS_ALLOW_CREDENTIALS = True
CORS_ALLOWED_ORIGINS = [
"http://localhost:4200",
]
CORS_ALLOWED_ORIGINS = [
"http://localhost:4200", # URL del frontend Angular
]
CORS_ALLOW_CREDENTIALS = True
CORS_ALLOW_HEADERS = [
'content-type',
'authorization',
]
CORS_ORIGIN_ALLOW_ALL = True
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",
]
MIDDLEWARE = [
'corsheaders.middleware.CorsMiddleware',
# altre middleware
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
# altre middleware
]
CORS_ORIGIN_WHITELIST = [
"http://localhost:8100"
]
MIDDLEWARE = [
'corsheaders.middleware.CorsMiddleware',
'django.middleware.security.SecurityMiddleware',
]
CORS_ALLOWED_ORIGINS = [
'http://localhost:4200',
]
CORS_ALLOW_METHODS = [
'GET',
'POST',
'PUT',
'PATCH',
'DELETE',
'OPTIONS',
'HEAD',
]
CORS_ORIGIN_ALLOW_ALL = True
CORS_ALLOW_CREDENTIALS = False
CORS_ALLOW_HEADERS = [
'content-type',
'authorization',
'x-requested-with',
]
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.AllowAny',
],
'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
'PAGE_SIZE': 10,
}
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
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'
这是我的 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>
结果是一个显示数据的页面,但如果我中断快速加载: 如果没有,API 将失败并出现 cors 错误。像这样:
我都试过了。
对于真正糟糕的代码和重复的代码感到抱歉,但我改变了太多,以至于我放弃了一次又一次地清理它。 请帮忙:(
您的代码有如此多的重复项,我认为找到错误原因并不容易。 如果你清理它并在 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 清理浏览器缓存。
如果有效请告诉我。