django 解决Access-Control-Allow-Origin跨域方案

1、安装跨域插件:pip install django-cors-headers

2、APPS中添加:corsheaders

INSTALLED_APPS = [
    'corsheaders', # 解决请求跨域问题
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'rest_framework',
]

3、MIDDLEWARE中间件中添加:corsheadrs.middleware.CorsMiddleware

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'corsheaders.middleware.CorsMiddleware',  # 这个跨域配置必须放在CommonMiddleware的上方
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

4、请求跨域配置

# 解决请求跨域问题配置
# CORS_ORIGIN_ALLOW_ALL = True # 允许所有域名跨域或者下面的白名单设置
CORS_ORIGIN_REGEX_WHITELIST = [ # 可跨域白名单设置
   "http://192.168.1.112:8080", # 前段请求的IP地址
]
CORS_ALLOW_METHODS=("*") # 配置允许的请求方式
CORS_ALLOW_HEADERS = ("*") # 配置允许的请求头
CORS_ALLOW_CREDENTIALS = True #允许携带cookie

5、完成跨域请求了

你可能感兴趣的:(Django,Python,conda,django,python,后端,跨域,Access-Control)