设置default_headers
首先先安装corsheaders pip3 install corsheaders
然后进入settings.py中导入 default_headers
并在下方加入
from corsheaders.defaults import default_headers
# 前端跨域相关
CORS_ORIGIN_ALLOW_ALL = True
# 允许ajax跨域请求时携带cookie
CORS_ALLOW_CREDENTIALS = True
# 跨域需要的headers
CORS_ALLOW_HEADERS = default_headers
SESSION_COOKIE_SAMESITE = None # response header set-cookie:samesite=lax Default: 'Lax'
CSRF_COOKIE_SAMESITE = None
之后修改修改默认自带的中间件
MIDDLEWARE = [
'corsheaders.middleware.CorsMiddleware',
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'corsheaders.middleware.CorsMiddleware', # 在这里要添加corsheaders中间件
'django.middleware.common.CommonMiddleware',
# 'django.middleware.csrf.CsrfViewMiddleware', 需要把csrf验证给注释掉
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]