设置default_headers

首先先安装corsheaders
pip3 install corsheaders
然后进入settings.py中导入 default_headers
并在下方加入

  1. from corsheaders.defaults import default_headers
  2. # 前端跨域相关
  3. CORS_ORIGIN_ALLOW_ALL = True
  4. # 允许ajax跨域请求时携带cookie
  5. CORS_ALLOW_CREDENTIALS = True
  6. # 跨域需要的headers
  7. CORS_ALLOW_HEADERS = default_headers
  8. SESSION_COOKIE_SAMESITE = None # response header set-cookie:samesite=lax Default: 'Lax'
  9. CSRF_COOKIE_SAMESITE = None

之后修改修改默认自带的中间件

  1. MIDDLEWARE = [
  2. 'corsheaders.middleware.CorsMiddleware',
  3. 'django.middleware.security.SecurityMiddleware',
  4. 'django.contrib.sessions.middleware.SessionMiddleware',
  5. 'corsheaders.middleware.CorsMiddleware', # 在这里要添加corsheaders中间件
  6. 'django.middleware.common.CommonMiddleware',
  7. # 'django.middleware.csrf.CsrfViewMiddleware', 需要把csrf验证给注释掉
  8. 'django.contrib.auth.middleware.AuthenticationMiddleware',
  9. 'django.contrib.messages.middleware.MessageMiddleware',
  10. 'django.middleware.clickjacking.XFrameOptionsMiddleware',
  11. ]