如何解决 Flutter 前端 Heroku 上 Django 后端的 CORS 问题?

问题描述 投票:0回答:1

我正在开发 Heroku 上托管的 Django 后端和 https://anirni.web.app 上托管的 Flutter 前端。由于 CORS 政策,我的 API 请求被阻止,我正在努力配置 Django 以正确处理此问题

**我当前的设置: **

  • 后端:Django 托管在 Heroku 上。
  • 前端:Flutter 应用程序托管在 https://anirni.web.app 上,并在本地进行了测试 (http://localhost:52360)。
  • CORS 库:我正在使用 django-cors-headers。

**我的settings.py的相关部分: **

`

"""
Django settings for anirni_server 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/
"""
import os
from pathlib import Path
import dj_database_url
from corsheaders.defaults import default_headers


EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
EMAIL_HOST = 'mail.anirni-dz.com'  # Remplacez par le serveur SMTP de Bluehost
EMAIL_PORT = 465  # Port SMTP (généralement 587 pour TLS)
EMAIL_USE_TLS = False
EMAIL_USE_SSL = True  # Activer SSL
EMAIL_HOST_USER = '###'  # Adresse email
EMAIL_HOST_PASSWORD = '###'  # Mot de passe
DEFAULT_FROM_EMAIL = '###'

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




# 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 = '####'

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


# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',  # Assurez-vous qu'elle est avant les autres apps comme 'auth'
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'rest_framework',
    "django_filters",
    'corsheaders',
    'rest_framework_simplejwt.token_blacklist',  # Pour la gestion des tokens JWT
    "django_crontab",
    'basic_rest',
    
]



CORS_ALLOW_METHODS = list(default_methods) + ["PATCH"]


REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework.authentication.BasicAuthentication',
        'rest_framework_simplejwt.authentication.JWTAuthentication',
        'rest_framework.authentication.SessionAuthentication',  # Optionnel pour l'authentification par session
    ),
    'DEFAULT_PERMISSION_CLASSES': (
        'rest_framework.permissions.IsAuthenticated',
    ),

    'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
    'PAGE_SIZE': 20  # Nombre de résultats par page
}



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

]

MIDDLEWARE.insert(0, 'basic_rest.middleware.LogHeadersMiddleware')


CORS_ALLOWED_ORIGINS = [
    "https://anirni.web.app",   # Domaine de votre application Flutter
    "http://localhost:52360",  # Pour le développement local
    
]


ALLOWED_HOSTS = ['anirni.web.app', 'anirnirest-f97872c47bed.herokuapp.com']

CORS_ALLOW_CREDENTIALS = True  # Autoriser les cookies/credentials
CORS_ALLOW_HEADERS = list(default_headers) + [
    "authorization",
    "x-requested-with",
]
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
SECURE_SSL_REDIRECT = True
SESSION_COOKIE_SECURE = True
CSRF_COOKIE_SECURE = True
ROOT_URLCONF = 'anirni_server.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 = 'anirni_server.wsgi.application'


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

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': os.getenv('DB_NAME',"###"),
        'USER': os.getenv('DB_USER',"###"),
        'PASSWORD': os.getenv('DB_PASSWORD',"####"),
        'HOST': os.getenv('DB_HOST',"###"),
        'PORT': os.getenv('DB_PORT',"5432"),
    }
}

DATABASES = {
    'default': dj_database_url.config(conn_max_age=600, ssl_require=True)
}

# 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/'
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATICFILES_DIRS = [os.path.join(BASE_DIR, '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'

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'handlers': {
        'console': {
            'class': 'logging.StreamHandler',
        },
    },
    'loggers': {
        'django': {
            'handlers': ['console'],
            'level': 'INFO',  # Niveau minimal de log (DEBUG, INFO, WARNING, ERROR, CRITICAL)
        },
        '__main__': {  # Logger pour le middleware personnalisé
            'handlers': ['console'],
            'level': 'INFO',
        },
    },
}




# Configurer la durée du token
from datetime import timedelta

SIMPLE_JWT = {
    'ACCESS_TOKEN_LIFETIME': timedelta(minutes=60),
    'REFRESH_TOKEN_LIFETIME': timedelta(days=7),
    'ROTATE_REFRESH_TOKENS': True,
    'BLACKLIST_AFTER_ROTATION': True,
    'AUTH_HEADER_TYPES': ('Bearer',),
}

**到目前为止我已经尝试过: **

  • 暂时添加 CORS_ALLOW_ALL_ORIGINS = True,但问题仍然存在。
  • 验证 HTTPS 已启用并且 Heroku 正确地将 HTTP 重定向到 HTTPS。
  • 使用curl和Postman进行测试,响应看起来不错,但来自Flutter的请求由于CORS而被阻止。

**预期行为: ** Flutter 前端应该能够向 Django 后端发送请求(包括 OPTIONS 预检请求)而不被阻塞。

**Flutter 和浏览器控制台出现错误: **

从源“https://anirni.web.app”访问“https://anirnirest-f97872c47bed.herokuapp.com/get_user_info”处的 XMLHttpRequest 已被 CORS 策略阻止:无“Access-Control-Allow-Origin”标头存在于请求的资源上。

**其他详细信息: **

  • API 使用带有基于令牌的身份验证 (JWT) 的 Rest_framework。
  • 我已确认我的 API 端点正在独立工作。
  • 用于令牌检索的 API 和公共 API 运行良好。但是,所有需要身份验证(使用 JWT)的 API 都被阻止。
django flutter heroku cors django-cors-headers
1个回答
0
投票

只需运行此命令

python manage.py runserver 0.0.0.0:8000

而不是

python manage.py runserver

另外,您可以在第一个命令中更改端口,我刚刚使用了默认端口

© www.soinside.com 2019 - 2024. All rights reserved.