如何在django后端和react js前端之间处理cors头

pbwdgjma  于 2023-06-25  发布在  Go
关注(0)|答案(1)|浏览(132)

我在www.example.com上运行react jsfrontend.domain.com,在www.example.com上运行后端backend.domain.com。我试图使用backend.domain.com url从后端django API获取数据。但是我得到了这个错误:
CORS策略已阻止从源“https://www.example.com”访问“https://backend.domain.com/login/”frontend.domain.com:请求的资源上不存在“Access-Control-Allow-Origin”标头。如果一个不透明的响应满足了你的需求,将请求的模式设置为“no-cors”,以在禁用CORS的情况下获取资源。
在我的django后端API中应该设置什么,比如在settings.py或任何其他地方。或者在前端react js?
使用frontend react js访问django的资源需要做什么改变?
如何处理这个错误,我应该在后端做什么改变来访问前端react js

efzxgjgh

efzxgjgh1#

按照这些步骤...

install(pip install django-cors-headers

settings.py

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',
    'rest_framework',
    'corsheaders', # <-------- this
    'myapp',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'corsheaders.middleware.CorsMiddleware', # <-------- this
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'sales_company_app.get_user_instance.RequestMiddleware',
]


REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework.authentication.TokenAuthentication',
    ),
}

CORS_ORIGIN_ALLOW_ALL = True # <-------- this
CORS_ALLOWED_ORIGINS = [
    "http://localhost:3000",    # React (FrontEnd Url) # <-------- this
]

CORS_ALLOW_HEADERS = '*' # <-------- this
CSRF_TRUSTED_ORIGINS = ["http://192.168.1.155:8000/"] # (Api Base Url) <-------- this (allow csrf_token) for doing whitelist

相关问题