django strict-origin-when-cross-origin 跨域

安装 django-cors-headers

pip install  django-cors-headers

将corsheaders添加到全局配置文件的INSTALLED_APPS中,尽量放在前面

INSTALLED_APPS = [
    'corsheaders',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'rest_framework',
    'django_filters',
]

添加中间件: corsheaders.middleware.CorsMiddleware

需要添加在CommonMiddleware中间件前面(必须)

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    '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',
]

添加白名单

# CORS_ORIGIN_ALLOW_ALL为True, 指定所有域名(ip)都可以访问后端接口, 默认为False
CORS_ORIGIN_ALLOW_ALL = True


# 也可以通过白名单列表添加指定的ip或域名

# CORS_ORIGIN_WHITELIST指定能够访问后端接口的ip或域名列表
CORS_ORIGIN_WHITELIST = [
    'http://127.0.0.1:8080',
    'http://localhost:8080'
# CORS_ALLOW_CREDENTIALS允许跨域时携带Cookie,默认为False
CORS_ALLOW_CREDENTIALS = True

原文链接: django strict-origin-when-cross-origin 跨域 版权所有,转载时请注明出处,违者必究。
注明出处格式:流沙团 ( https://www.gyarmy.com/post-793.html )

发表评论

0则评论给“django strict-origin-when-cross-origin 跨域”