Loading

Django-setting配置之cors跨域

1.Django-setting配置之cors跨域


1.1 安装

pip install django-cors-headers

1.2 在setting.py中添加应用

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

1.3 在setting.py的中间件中添加

注意:一定要在'corsheaders.middleware.CorsMiddleware',后面添加,(逗号)否则会报跨域的错

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

1.4添加白名单

# 设置cors跨域请求白名单 凡是出现在白名单中的域名,都可以访问后端接口
CORS_ORIGIN_WHITELIST = (
    'http://127.0.0.1:8080',
    'http://localhost:8080',
    'http://127.0.0.1:8081',
    'http://localhost:8081',
    'http://127.0.0.1:8888',
    'http://localhost:8888',
)

1.5指明在跨域访问中,后端是否支持对cookie的操作

CORS_ALLOW_CREDENTIALS = True

posted @ 2020-10-26 11:26  就学45分钟  阅读(323)  评论(0编辑  收藏  举报