解决Django跨域访问的问题

1、安装django-cors-headers模块

pip install django-cors-headers

2、插入Django的APP配置中

# 修改settings.py中的INSTALLED_APPS配置
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    # 新插入的corsheaders,之前的不变
    'corsheaders',  
]

3、注册CorsMiddleware中间件

# 插入CorsMiddleware到中间件列表
MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    # 插入CorsMiddleware到中间件列表,位置不能错
    'corsheaders.middleware.CorsMiddleware',
    # --------------------------------------
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

CorsMiddleware中间件放置的位置不能错

4、配置文件中的设置

CORS_ORIGIN_ALLOW_ALL = True

配置上述一个配置项django接口就可以跨域访问,下面是网上找的完整配置

CORS_ALLOW_CREDENTIALS = True
CORS_ORIGIN_ALLOW_ALL = True

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',
)

不知道其他的配置需不需要,留作以后再说!

原文地址:https://www.cnblogs.com/carp-li/p/13854611.html