我已经安装了django-cors-headers,下面是settings.py:
ALLOWED_HOSTS = os.environ.get("ALLOWED_HOSTS","").split()
MIDDLEWARE = [
'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.RemoteUserMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
和
CORS_ALLOW_ALL_ORIGINS = True
CORS_ALLOW_CREDENTIALS = True
但是我在chrome控制台得到了这个错误:
Access to XMLHttpRequest at 'https://event-alpha.mizbans.com/api/meetings/?memory=0' from origin 'https://alpha.mizbans.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
我有一个类似的问题,都是关于CORS_ALLOW_ALL_ORIGINS。事实证明,它不能很好地与其他东西一起工作(对不起,我不记得是什么了,可能是身份验证)。所以我必须添加特定的起源。这是我的整个设置:
# CORS SETUP
CORS_ALLOW_CREDENTIALS = True
CORS_ALLOWED_ORIGINS = [
'http://localhost:4200',
'http://127.0.0.1:4200'
]
CSRF_COOKIE_HTTPONLY = True
SESSION_COOKIE_HTTPONLY = True
SESSION_COOKIE_SAMESITE = 'None'
CSRF_COOKIE_SAMESITE = 'None'
对我来说,这个组合现在可以工作了。