不能在有Angular 的前端嵌入django后端html

carvr3hs  于 2021-07-14  发布在  Java
关注(0)|答案(0)|浏览(449)

如问题中所述,我正在尝试将位于django后端的html表单网页嵌入前端(在另一台服务器中使用angular制作),但当我访问前端页面(嵌入后端页面的位置)时,出现以下错误:

[Error] Blocked autofocusing on a form control in a cross-origin subframe.
[Error] Blocked a frame with origin "https://...{backend address}..." from accessing a frame with origin "http://...{frontend address}...".  The frame requesting access has a protocol of "https", the frame being accessed has a protocol of "http". Protocols must match. (x8)

[Error] Refused to display 'https://...{backend address}.../register_student' in a frame because it set 'X-Frame-Options' to 'SAMEORIGIN'.
[Error] Failed to load resource: the server responded with a status of 403 () (register_student, line 0)

为了解决这个问题,我修改了settings.py文件

MIDDLEWARE = [
...
'django.middleware.clickjacking.XFrameOptionsMiddleware',
...
]

SESSION_COOKIE_DOMAIN=".ynsat.com"
X_FRAME_OPTIONS = 'SAMEORIGIN'

我还用以下信号修改了views.py:

@xframe_options_exempt
def register_student(request):
...

问题是前端页面正确地显示了iframe,但是当它发送表单时,上面显示的错误就出现了。
这是我的密码:
视图.py

...
@xframe_options_exempt
def register_student(request):
    if request.method == 'POST':
        form = StudentRegisterForm(request.POST)

        if form.is_valid():
            form.save()
            username = form.cleaned_data['username']
            messages.success(request, f'Bienvenido {username}!')

            return redirect('register_student')
        else:
            pass
    else:
        form = StudentRegisterForm()

    context = {'form': form}
    return djRender(request, 'register_student.html', context)

def register_teacher(request):
    if request.method == 'POST':
        form = TeacherRegisterForm(request.POST)

        if form.is_valid():
            form.save()
            username = form.cleaned_data['username']
            messages.success(request, f'Bienvenido {username}!')

            return redirect('register_teacher')
        else:
            pass
    else:
        form = TeacherRegisterForm()

    context = {'form': form}
    return djRender(request, 'register_teacher.html', context)

设置.py

from pathlib import Path
import os

BASE_DIR = Path(__file__).resolve().parent.parent

SECRET_KEY = 'r(rw(w*3=mw@0-r*$t1q0zejf*#3il#wy)#4+4c2c934w@2%)j'

DEBUG = True

ALLOWED_HOSTS = ['*']

# Application definition

INSTALLED_APPS = [
    'rest_framework',
    'rest_framework.authtoken',
    'corsheaders',
    ...
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]

MIDDLEWARE = [

    'django.middleware.clickjacking.XFrameOptionsMiddleware',

    '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',
]

ROOT_URLCONF = 'DjangoServer.urls'

TEMPLATES = [
    {
        'BACKEND': '...',
        '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 = 'DjangoServer.wsgi.application'

import pymysql
pymysql.version_info = (1, 4, 6, 'final', 0)  # change mysqlclient version
pymysql.install_as_MySQLdb()

if os.getenv('GAE_APPLICATION', None):
    DATABASES = {
        'default': {
            'ENGINE': '...',
            'HOST': '...',
            'USER': '...',
            'PASSWORD': '...',
            'NAME': '...',
        }
    }
else:
    DATABASES = {
        'default': {
            'ENGINE': '...mysql',
            'HOST': '...',
            'PORT': '3306',
            'NAME': '...',
            'USER': '...',
            'PASSWORD': '...',
        }
    }
if os.getenv('TRAMPOLINE_CI', None):
    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.sqlite3',
            'NAME': os.path.join(BASE_DIR, 'db.sqlite3')
        }
    }

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',
    },
]

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'Europe/Madrid'

USE_I18N = True

USE_L10N = True

USE_TZ = True

CORS_ALLOW_ALL_ORIGINS = True

STATIC_URL = 'static/'
STATIC_ROOT = 'static'

MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

REST_FRAMEWORK = {
   'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework.authentication.TokenAuthentication',
        'rest_framework.authentication.SessionAuthentication',
   ),
   'DEFAULT_PERMISSION_CLASSES': (
        'rest_framework.permissions.IsAdminUser',
   ),
}

SITE_ID = 0
""" LOGIN_REDIRECT_URL = '/' """

SESSION_COOKIE_DOMAIN=".ynsat.com"

X_FRAME_OPTIONS = 'SAMEORIGIN'

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题