安装django-cors-headers

1、安装django-cors-headers 实现cors

安装django-cors-headers插件:

  • pip install django-cors-headers

使用时在对应的Django项目settings.py中做以下修改:



#将corsheaders 注册到app中
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'corsheaders',
    'app01',
]

#3、将下面两条添加到中间件重
MIDDLEWARE = [
    'corsheaders.middleware.CorsMiddleware',
]

#4、配置 django-cors-headers 中的参数
CORS_ALLOW_CREDENTIALS = True  # 允许携带cookie
CORS_ORIGIN_ALLOW_ALL = True   # 允许所有源访问
CORS_ORIGIN_WHITELIST = (
    'http://127.0.0.1:8000',    #设置白名单
    'http://localhost:8000',
)

CORS_ALLOW_METHODS = (
    'DELETE',                 #允许的方法
    'GET',
    'OPTIONS',
    'PATCH',
    'POST',
    'PUT',
    'VIEW',
)

CORS_ALLOW_HEADERS = (
    'XMLHttpRequest',
    'X_FILENAME',
    'accept-encoding',
    'authorization',          #允许的请求头
    'content-type',
    'dnt',
    'origin',
    'user-agent',
    'x-csrftoken',
    'x-requested-with',
    'Pragma',
)

settings.py

猜你喜欢

转载自blog.csdn.net/dasfa11/article/details/108857748