django 使用django-cors-headers 解决跨域问题

django-cors-headers

'''
浏览器具有 "同源策略的限制",导致 发送ajax请求 + 跨域 存在无法获取数据。

- 简单请求,发送一次请求。
- 复杂请求,先options请求做预检,然后再发送真正请求
'''

1、使用pip安装

pip install django-cors-headers

2、添加到setting的app中

INSTALLED_APPS = (
...
'corsheaders',
...
)

3、添加中间件

MIDDLEWARE = [ # Or MIDDLEWARE_CLASSES on Django < 1.10
...
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware',
...
]

4、setting下面添加下面的配置

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 = (
'XMLHttpRequest',
'X_FILENAME',
'accept-encoding',
'authorization',
'content-type',
'dnt',
'origin',
'user-agent',
'x-csrftoken',
'x-requested-with',
'Pragma',
)

posted @ 2019-12-16 21:36  阿浪阿浪  阅读(3503)  评论(0)    收藏  举报