django - 请求的资源 Django 和 ReactJS 上不存在“Access-Control-Allow-Origin”标头
问题描述
目前我有Django 1.98作为后端和 React 作为前端。
我收到此错误:
从源“ http://localhost:3000 ”访问“ https://mywebsite:8000/uploads/vtt/ ”的 XMLHttpRequest已被 CORS 策略阻止:不存在“Access-Control-Allow-Origin”标头请求的资源。
我在我的虚拟环境上安装了django-cors-headers==2.4.0
这是我的settings.py文件:
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'uploads.core',
'corsheaders',
]
MIDDLEWARE_CLASSES = [
'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.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
CORS_ORIGIN_ALLOW_ALL = True
CSRF_TRUSTED_ORIGINS = ['http://127.0.0.1:3000','http://localhost:3000','http://localhost:8000','https://mywebsite:8000','https://myapp.firebaseapp.com','https://mywebsite:8088']
CSRF_COOKIE_NAME = "csrftoken"
CSRF_HEADER_NAME = [
'HTTP_X_CSRFTOKEN'
]
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
SECURE_SSL_REDIRECT = True
SESSION_COOKIE_SECURE = True
CSRF_COOKIE_SECURE = True
CORS_ORIGIN_WHITELIST = ['http://localhost:3000','https://mywebsite:8088']
CORS_ALLOW_METHODS = (
'DELETE',
'GET',
'OPTIONS',
'PATCH',
'POST',
'PUT',
)
CORS_ALLOW_HEADERS = (
'accept',
'accept-encoding',
'authorization',
'content-type',
'dnt',
'origin',
'user-agent',
'x-csrftoken',
'x-requested-with',
)
知道如何解决吗?谢谢。
解决方案
确保https://mywebsite:8000/uploads/vtt/
是正确的 URL。
就我而言,我使用了错误的端口,因为我的 API 使用了不同的端口。
我替换8000
为52130
.