我试图从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错误。这样地:
我都试过了。
我还从前端开始使用:ng-serve--proxy-config-src/proxy.conf.json。
这是代理:
{
"/api": {
"target": "http://127.0.0.1:8000",
"secure": false,
"changeOrigin": true,
"logLevel": "debug"
}
}
很抱歉出现了真正糟糕的代码和重复的代码,但我改变了太多,以至于我放弃了一次又一次地清理它。
请帮忙:(