问题描述
开发前后端分离项目,并且前后端服务器需要跨域来交互,直接用fetch会出问题,后端Django无法获取数据。
配置方法
前端fetch使用mode: 'cors'
后端Django,安装django-cors-headers
在settings.py
中设置:
INSTALLED_APPS = [
'corsheaders',
]
MIDDLEWARE = [
#...,
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware',
#...,
]
# 允许携带credentials,即cookies(只会带该域名的cookies哦)。
CORS_ALLOW_CREDENTIALS = True
# If True, cookies will be allowed to be included in cross-site HTTP requests. Defaults to False.
# Note: in Django 2.1 the SESSION_COOKIE_SAMESITE setting was added, set to 'Lax' by default, which
# will prevent Django's session cookie being sent cross-domain. Change it to None to bypass this
# security restriction.
# 设置Allow all虽然简单粗暴,但是并不推荐,可能有安全风险。曾经的版本该配置叫CORS_ORIGIN_ALLOW_ALL,效果相同。默认值False
CORS_ALLOW_ALL_ORIGINS = True
# 推荐方式1,可以这样指定域名
CORS_ALLOWED_ORIGINS = [
"https://example.com",
"https://sub.example.com",
"http://localhost:8080",
"http://127.0.0.1:9000"
]
# 推荐方式2,正则匹配域名
CORS_ALLOWED_ORIGIN_REGEXES = [
r"^https://\w+\.example\.com$",
]
# 设置允许的methods。以下是默认值
CORS_ALLOW_METHODS = [
'DELETE',
'GET',
'OPTIONS',
'PATCH',
'POST',
'PUT',
]
# 设置允许的headers。以下是默认值
CORS_ALLOW_HEADERS = [
'accept',
'accept-encoding',
'authorization',
'content-type',
'dnt',
'origin',
'user-agent',
'x-csrftoken',
'x-requested-with',
]
注意corsheaders.middleware.CorsMiddleware
必须放在django.middleware.common.CommonMiddleware
的上面。
然后就可以看到数据啦!
更多django-cors-headers配置项,可参考:
https://pypi.org/project/django-cors-headers/
https://github.com/adamchainz/django-cors-headers