安装

  1. pip install django-cors-headers

配置文件

  1. # 注册app
  2. INSTALLED_APPS = [
  3. ...
  4. 'corsheaders',
  5. ]
  6. # 添加中间件
  7. MIDDLEWARE = [
  8. ...
  9. 'corsheaders.middleware.CorsMiddleware',
  10. ]
  11. # 允许跨域源
  12. CORS_ORIGIN_ALLOW_ALL = True
  13. CORS_ALLOW_CREDENTIALS = True
  14. # 允许的请求头
  15. CORS_ALLOW_HEADERS = (
  16. "accept",
  17. "accept-encoding",
  18. "authorization",
  19. "content-type",
  20. "dnt",
  21. "origin",
  22. "user-agent",
  23. "x-csrftoken",
  24. "x-requested-with",
  25. # 额外允许的请求头
  26. 'token',
  27. )
  28. CORS_ALLOW_METHODS = (
  29. 'DELETE',
  30. 'GET',
  31. 'OPTIONS',
  32. 'PATCH',
  33. 'POST',
  34. 'PUT',
  35. 'VIEW',
  36. )