Django跨域问题解决方案: django-cors-headers安装与配置

django-cors-headers安装与配置

官方文档:https://pypi.org/project/django-cors-headers/

安装

pip install django-cors-headers

使用

添加到settings.py中, 按如下进行配置

# settings.py
INSTALLED_APPS = [
    'corsheaders',
]

MIDDLEWARE = [
    ...
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.common.CommonMiddleware',
    ...
]

# 在settings.py文件末尾添加如下配置
# 跨域增加忽略
CORS_ALLOW_CREDENTIALS = True
CORS_ORIGIN_ALLOW_ALL = True
CORS_ORIGIN_WHITELIST = (
    # 这里添加你允许的跨域来源
    'http://127.0.0.1',
)

# 添加运行的请求方法
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',
)

至此问题解决

博观而约取,厚积而薄发
原文地址:https://www.cnblogs.com/leoych/p/15320669.html