我正在开发一个带有 React 前端、Django 后端、在 gitpod 中开发的项目。我相信 gitpod 可能比我想象的更复杂。
目前,我可以确认我能够运行 python manage.py runserver,然后通过 api 根浏览 Django Rest Framework。
我还有一个 Create-React_app 前端,它能够向另一个 API 发出请求,但对我的 API 的请求仅返回错误: “可以从来源“https://3000-anthonydeva-sylvanlibra-8b5cu5lyhdl.ws-us107.gitpod”获取“https://8000-anthonydeva-sylvanlibra-8b5cu5lyhdl.ws-us107.gitpod.io/lineitem/”。 io' 已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:请求的资源上不存在 'Access-Control-Allow-Origin' 标头。如果不透明响应满足您的需求,请设置请求的模式设置为“no-cors”以在禁用 CORS 的情况下获取资源。”
根据我到目前为止所看到的情况,我知道 django-cors-headers 是推荐的解决方案,但即使在 settings.py 中安装和设置后,也会出现相同的错误,而我的 django 服务器没有似乎显示了失败请求的任何更新。
如果缺少任何所需信息,我深表歉意。我对此还很陌生,在识别什么是不必要的、什么是有用的方面遇到了一些困难。我很乐意分享所需的任何其他信息。
INSTALLED_APPS = [
'corsheaders',
# 'django_filters',
'library.apps.LibraryConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
]
MIDDLEWARE = [
"corsheaders.middleware.CorsMiddleware",
'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',
]
# CORS_ALLOWED_ORIGINS = [
# 'https://3000-anthonydeva-sylvanlibra-37g1pm5kjx9.ws-us107.gitpod.io',
# ]
CORS_ALLOW_ALL_ORIGINS = True
CORS_ORIGIN_ALLOW_ALL = True #I have seen both of these, so I tried both
# CORS_ORIGIN_WHITELIST = [
# 'https://3000-anthonydeva-sylvanlibra-8b5cu5lyhdl.ws-us107.gitpod.io/'
# ]
ALLOWED_HOSTS = [ '*' ]
CORS_ALLOW_HEADERS = [ '*' ]
CSRF_TRUSTED_ORIGINS = [ 'https://***.gitpod.io' ]
ROOT_URLCONF = 'sylvan.urls'
CORS_ALLOW_CREDENTIALS = False
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 = 'sylvan.wsgi.application'
在你的settings.py中试试这个
CORS_ALLOW_ALL_ORIGINS = False
CORS_ALLOWED_ORIGINS = [
"http://localhost:3000",
]