django跨域设置

Django 跨域问题,解决前后端连接 CORS

1.安装 django-cors-headers

pip install django-cors-headers

2.配置settings

在 INSTALLED_APPS 里添加 “corsheaders”

INSTALLED_APPS = [
    ...
    'corsheaders',
    ...
 ]

在 MIDDLEWARE_CLASSES 添加

重点:
cors-headers的中间件CorsMiddleware在注册时必须放在django-common中间件的前一个
如何有重复配置也要删除掉之前的,不然会导致配置失效。

MIDDLEWARE_CLASSES = (
    ...
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.common.CommonMiddleware', 
    ...
)

 

在底部新增

# 跨域增加忽略
CORS_ALLOW_CREDENTIALS = True
CORS_ORIGIN_ALLOW_ALL = True
CORS_ORIGIN_WHITELIST = ()
CORS_ALLOW_METHODS = (
    'DELETE',
    'GET',
    'OPTIONS',
    'PATCH',
    'POST',
    'PUT',
    'VIEW',
) 
CORS_ALLOW_HEADERS = (
    'accept',
    'accept-encoding',
    'authorization',
    'content-type',
    'dnt',
    'origin',
    'user-agent',
    'x-csrftoken',
    'x-requested-with',
)

 

posted @ 2023-05-08 09:42  Mrterrific  阅读(262)  评论(0编辑  收藏  举报